>
>
>
V1045. The DllMain function throws an e…


V1045. The DllMain function throws an exception. Consider wrapping the throw operator in a try..catch block.

The analyzer has detected a block of code that throws an exception inside the body of the DllMain function but does not catch it.

When loading and attaching a dynamic library to the current process, this function takes the value DLL_PROCESS_ATTACH for the 'fwdReason' parameter. If DllMain terminates with an error, it must return the value FALSE. The loader then calls it again with the value DLL_PROCESS_DETACH for 'fwdReason', thus causing the DLL library to unload. If DllMain terminates as a result of throwing an exception, the library remains attached to the processed.

Example of non-compliant code:

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
  ....
  throw 42;
  ....
}

The program should handle the exception in a try...catch block and return FALSE correctly.

Fixed version:

BOOL __stdcall DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
  try
  {
    ....
    throw 42;
    ....
  }
  catch(...)
  {
    return FALSE;
  }
}

An exception can also occur when calling the 'new' operator. If memory allocation fails, a 'bad_alloc' exception will be raised, for example:

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
  ....
  int *localPointer = new int[MAX_SIZE];
  ....
}

An exception can also occur when handling references using dynamic_cast<Type>. If type cast is impossible, a 'bad_cast' exception will be raised, for example:

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
  ....
  UserType &type = dynamic_cast<UserType&>(baseType);
  ....
}

To fix errors like that, rewrite the code so that 'new' or 'dynamic_cast' are wrapped in a try...catch block.

The analyzer also detects calls to functions that could potentially throw an exception in 'DllMain', for example:

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
  ....  
  potentiallyThrows();
  ....
}

If no operations capable of throwing an exception are found in the callee's code, the analyzer will not report this call.

Similarly, calls to functions that could throw an exception should be wrapped in a try...catch block.

This diagnostic is classified as: