Neon Flash Neon Flash - 2 months ago 12
C Question

DLL Export Function Called Twice

I have made a short DLL which will display a MessageBox when it is loaded by a process. However, the message box is displayed two times. So, it looks like the DLL Export Function is called twice. Could you please see if there is something that needs to be modified in my code so that the MessageBox is displayed only once?

#include <windows.h>
#include <stdio.h>

__declspec(dllexport) void sampledllmain()
{
MessageBox(NULL, "sample text","sample title", 0);
}

BOOL APIENTRY DllMain(HANDLE hHandle, DWORD dwReason, LPVOID Reserved)
{
switch(dwReason)
{
case DLL_PROCESS_ATTACH:
sampledllmain();
break;
}
return 1;
}


I load the DLL using rundll32 as shown below:

rundll32 "path to DLL",sampledllmain

Answer

As described by the information page about rundll32.exe :

  1. It loads the specified DLL via LoadLibrary().
  2. It obtains the address of the function via GetProcAddress().
  3. It calls the function, passing the command line tail which is the .

In your case :

  1. When LoadLibrary() is invoked it calls DllMain, in your case DllMain calls sampledllmain.
  2. Obtains the address of sampledllmain
  3. calls sampledllmain ( second time ).

to fix your issue:

  • add a second function dummy (for example )
  • use rundll32 "path to DLL",dummy on the command line

PS: On an additional note you could also debug your dll there are guides that describe how to do it

An example with MessageBox call in dllMain

#include <windows.h>
__declspec(dllexport) void sample(void)
{
    MessageBox(NULL, "sample text test", "sample title test", 0);
}
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        MessageBox(NULL, "attach", "DllMain", 0);
        break;
    case DLL_THREAD_ATTACH:
        break;
    case DLL_THREAD_DETACH:
        break;
    case DLL_PROCESS_DETACH:
        MessageBox(NULL, "detach", "DllMain", 0);
        break;
    }
    return TRUE;
}

Run with rundll32.exe lib.dll,sample

Comments