PRB: LoadLibrary() Fails with _declspec(thread)

ID: Q118816

1.10 1.15 1.20 1.25a 4.00 | 3.50 3.51 4.00

WINDOWS                   | WINDOWS NT
kbprg

The information in this article applies to:

SYMPTOMS

Your dynamic-link library (DLL) uses __declspec(thread) to allocate thread local storage (TLS). There are no problems running an application that is statically linked with the DLL's import library. However, when an application uses LoadLibrary() to load the DLL instead of using the import library, LoadLibrary() fails on Win32s with "error 87: invalid parameter". LoadLibrary() succeeds under Windows NT in this situation; however, the application cannot successfully call functions in the DLL.

CAUSE

This is a limitation of LoadLibrary() and __declspec(). The global variable space for a thread is allocated at run time. The size is based on a calculation of the requirements of the application plus the requirements of all of the DLLs that are statically linked. When you use LoadLibrary(), there is no way to extend this space to allow for the thread local variables declared with __declspec(thread). This can cause a protection fault either when the DLL is dynamically loaded or code references the data.

RESOLUTION

DLLs that use __declspec(thread) should not be loaded with LoadLibrary().

Use the TLS APIs, such as TlsAlloc(), in your DLL to allocate TLS if the DLL might be loaded with LoadLibrary(). If you continue to use _declspec(), warn users of the DLL that they should not load the DLL with LoadLibrary().

KBCategory: kbprg kbprb KBSubcategory: BseDll Additional reference words: 1.10 1.15 1.20 1.25a 3.50 3.51 4.00 95

Keywords          : kbDLL kbKernBase kbGrpKernBase 
Version           : 1.10 1.15 1.20 1.25a 4.00 | 3.50
Platform          : NT WINDOWS

Last Reviewed: December 18, 1996