Free TLS Pointers for Each Topic

Reading the following page on MSDN:

Using local stream storage in a dynamic link library

I cannot understand who is responsible for freeing the memory indicated by the TLS slot of each thread in case of a call FreeLibrary().

From what I understand, if I have several threads running, they all allocate memory inside the TLS slot in this index. When it is called FreeLibrary(), it only starts DLL_PROCESS_DETACH, so only the thread that receives the notification DLL_PROCESS_DETACHhas the ability to call LocalFree()on its own data stored in the TLS slot before calling TlsFree()the index. This causes a memory leak in all other threads that are not able to call LocalFree()for their data because they do not receive a notification DLL_THREAD_DETACH.

Can someone explain when and where the buffers stored in the TLS slots of each stream should be freed?

+4
source share
1

, :

, DLL_THREAD_DETACH, .

, , TLS, , . :

case DLL_THREAD_DETACH:
    // Release the allocated memory for this thread.
    lpvData = TlsGetValue(dwTlsIndex);
    if (lpvData != NULL)
        LocalFree((HLOCAL) lpvData);
    break;

case DLL_PROCESS_DETACH:
    // Release the allocated memory for this thread.
    lpvData = TlsGetValue(dwTlsIndex);
    if (lpvData != NULL)
        LocalFree((HLOCAL) lpvData);
    // Release the TLS index.
    TlsFree(dwTlsIndex);
    break;

, DllMain entry point:

DLL - DLL, , FreeLibrary, DLL -point DLL_THREAD_DETACH . DLL DLL_PROCESS_DETACH. DLL , , DLL.

, , TLS, , , DLL_THREAD_DETACH, DLL_PROCESS_DETACH. , .


: DLL_PROCESS_DETACH, , TIB/TEB ( /) . NtQueryInformationThread() TIB/TEB, , TIB/TEB TLS-.


. Vista + - FLS ( ) TLS ( ). FlsAlloc() . FlsCallback :

, . FLS , FlsCallback , , FLS- .

FlsFree() :

FLS FLS . FLS , FLS , NULL.

Fibers:

(FLS) . , FLS , . FLS (FlsAlloc, FlsFree, FlsGetValue FlsSetValue) FLS, . , FLS .

+4

Source: https://habr.com/ru/post/1683799/


All Articles