1 /*
2  * Simple test application for Windows Thread Local Storage (TLS). It
3  * demonstrates both the use of TLS callbacks and TLS variables.
4  *
5  * Program flow:
6  *  1. When the main thread is created tls_callback is called and incrememnts
7  *     the TLS variable. In the main thread tls_i == 0xab
8  *  2. The main thread then creates myThread. Windows will then initialize a
9  *     new TLS data area for this thread. tls_i == 0xaa
10  *  3. tls_callback is called in myThread and increments tls_i. In myThread
11  *     tls_i == 0xab
12  *  4. myThread's entry point, thread_func, is then called and decrements
13  *     tls_i. tls_i == 0xaa. Note that in the main thread, tls_i == 0xab
14  *  5. thread_func returns and myThread is terminated. Its tls_i is
15  *     essentially deallocated
16  */
17 
18 #include <Windows.h>
19 
20 __declspec(thread) int tls_i = 0xaa;
21 
22 void NTAPI tls_callback(PVOID h, DWORD reason, PVOID reserved) {
23 	tls_i++;
24 }
25 
26 #pragma data_seg(".CRT$XLB")
27 PIMAGE_TLS_CALLBACK p_thread_callback = tls_callback;
28 #pragma data_seg()
29 
30 DWORD WINAPI thread_func(LPVOID lpParameter) {
31 	tls_i--;
32 
33 	return 0;
34 }
35 
36 int main(int argc, char *argv[]) {
37 	HANDLE myThread;
38 
rotl64(uint64_t x,int n)39 	myThread = CreateThread(NULL, 0, thread_func, NULL, 0, NULL);
40 	WaitForSingleObject(myThread, INFINITE);
41 
42 	// tls_i == 0xab in the main thread at this point in time
43 
44 	return 0;
45 }