Tuesday, March 15, 2011

Same DLL loaded twice in a process

I have an ActiveX control (foo.dll), when I embedded the same in the IE and start the page. I could see that the process explorer shows two instances of the foo.dll loaded from the same location.

This causes the DLL_PROCESS_ATTACH to be called twice and the global data structures gets initialized twice.

Is there a way to workaround this ? how does the windows loader works ?

Thanks, Velu

From stackoverflow
  • One workaround is to protect your global data with a singleton-ish initialize function.

    How many global structures do you have anyway?

  • DLL_PROCESS_ATTACH is called whenever a process loads the DLL.

    Use a counter to determine how many processes are attached, and only do initialization when the first one attaches.

    You also need to set things up to share memory between instances of the DLL, and store the counter in that, as well as your global memory that you only want to initialize once.

  • DLL_PROCESS_ATTACH should only be called once per instance of the DLL . . . are the DLL's loaded at the same base address, i.e., is the HINSTANCE in DllMain the same? Are they loaded from the exact same path? Different paths result in diffent loaded modules. Is it being unloaded in between the two loads? Are you sure you're seeing DLL_PROCESS_ATTACH and not DLL_THREAD_ATTACH?

    atVelu : Hi Micheal, Surprisingly both the instances gets loaded from the same path and the DLL_PROCESS_ATTACH is what I was referring to ..
    Michael : Is the DLL being unloaded in between? Can you post the code to your DllMain?
  • LoadLibraryEx contains an extra flag for how to treat the dll. I suspect this is why you see it appear more than once.

0 comments:

Post a Comment