TLS initialization callback

0001-01-01

A TLS initialization callback is a callback function specified in the TLS directory of a PE file that is executed when a process or thread starts or ends.

#include <Windows.h>

void NTAPI callback(PVOID DllHandle, DWORD Reason, PVOID Reserved) {
	switch (Reason) {
	case DLL_PROCESS_ATTACH:
		// program started
		break;
	case DLL_PROCESS_DETACH:
		// program ended
		break;
	case DLL_THREAD_ATTACH:
		// thread started
		break;
	case DLL_THREAD_DETACH:
		// thread ended
		break;
	}
}

Must use linker pragmas to add the function to TLS directory:

#pragma comment(linker, "/INCLUDE:_tls_used") // use TLS
#pragma comment(linker, "/INCLUDE:callback")  // my callback function

#ifdef _WIN64
#pragma const_seg(".CRT$XLB")
#else
#pragma data_seg(".CRT$XLB")

PIMAGE_TLS_CALLBACK p_tls_callback = callback;
#pragma data_seg()
#pragma const_seg()