In the following article, I share with you how to use TLS callbacks in your C/C++ program compiled with Visual Studio.
Background
TLS (thread local storage) callbacks are a mechanism provided by the Windows loader to give your program a chance to do initialization/deinitialization tasks when the process starts, terminates, a thread is created or terminated.
A TLS callback has the following prototype:
typedef VOID (NTAPI *PIMAGE_TLS_CALLBACK) ( PVOID DllHandle, DWORD Reason, PVOID Reserved);
The Reason argument can be any of the following constants:
- DLL_PROCESS_ATTACH = 1
- DLL_PROCESS_DETACH = 0
- DLL_THREAD_ATTACH = 2
- DLL_THREAD_DETACH = 3
The TLS callbacks are encoded inside the compiled program’s TLS data directory(IMAGE_DIRECTORY_ENTRY_TLS). Please refer to the PE file structure. Continue reading “Using C/C++ TLS callbacks in Visual Studio with your 32 or 64bits programs”