2

I have created a sample application based on the following MS link, https://msdn.microsoft.com/en-us/library/aa391769(v=vs.85).aspx

The only change I have done is putting the hole code inside a dll and loaded the particular dll in my sample win32 executable, using LoadLibrary call.

Dll code:

#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <wbemidl.h>

#pragma comment(lib, "wbemuuid.lib")

BOOL APIENTRY DllMain( HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    {
        HRESULT hResult;
        IWbemLocator*  locPtr;
        IWbemServices* servPtr;
        hResult =  CoInitializeEx( 0, COINIT_MULTITHREADED );
        //hResult =  CoInitializeSecurity( NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_NONE, RPC_C_IMP_LEVEL_ANONYMOUS, NULL, EOAC_NONE, NULL );
        hResult = CoCreateInstance( CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &locPtr);
        hResult = locPtr->ConnectServer( L"ROOT\\CIMV2", NULL, NULL, 0, 0 , 0, 0, &servPtr );
        hResult = CoSetProxyBlanket( servPtr, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE );
}
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
    break;
}
return TRUE;

}

And exe code:

int _tmain(int argc, _TCHAR* argv[])
{
    ::LoadLibrary(L"mydynamic.dll");
    return 0;
}

Code executed properly, dll loaded ok, however code stuck at locPtr->ConnectServer() call.

Most strange thing is that if I write the complete COM code in the exe, it works fine. But not with dll.

Any suggestions?

Note: library connectivity is done with wbemuuid.lib

Dipesh K
  • 21
  • 2

2 Answers2

0

https://msdn.microsoft.com/en-in/library/windows/desktop/dn633971(v=vs.85).aspx#general_best_practices

The above document says,

"You should never perform the following tasks from within DllMain:

  1. Call LoadLibrary or LoadLibraryEx (either directly or indirectly). This can cause a deadlock or a crash.

  2. Initialize COM threads by using CoInitializeEx. Under certain conditions, this function can call LoadLibraryEx.

  3. Call the registry functions. These functions are implemented in Advapi32.dll. If Advapi32.dll is not initialized before your DLL, the DLL can access uninitialized memory and cause the process to crash."

and so on.

We were performing CoInitializeEx() calls inside dllmain(), that was causing process hang

Dipesh K
  • 21
  • 2
0
BSTR strNetworkResource  = SysAllocString(L"ROOT\\CIMV2");
if (!FAILED(locator->ConnectServer(strNetworkResource, NULL, NULL, 0, NULL, 0, 0, &services))) { // your code goes here. }
SysFreeString(strNetworkResource);

The first parameter of the IWbemLocator::ConnectServer method must be passed as a non-read only memory. if this parameter is passed as a constant variable or a literal string the function may cause an access violation.