Reverse Engineering for Beginners

(avery) #1
CHAPTER 65. THREAD LOCAL STORAGE CHAPTER 65. THREAD LOCAL STORAGE

Chapter 65


Thread Local Storage


TLS is a data area, specific to each thread. Every thread can store what it needs there. One well-known example is the C
standard global variableerrno. Multiple threads may simultaneously call functions which return an error code inerrno, so
a global variable will not work correctly here for multi-threaded programs, soerrnomust be stored in theTLS.

In the C++11 standard, a newthread_local modifier was added, showing that each thread has its own version of the
variable, it can be initialized, and it is located in theTLS^1 :

Listing 65.1: C++11
#include <iostream>
#include <thread>

thread_local int tmp=3;

int main()
{
std::cout << tmp << std::endl;
};

Compiled in MinGW GCC 4.8.1, but not in MSVC 2012.

If we talk about PE files, in the resulting executable file, thetmp variable is to be allocated in the section devoted to the
TLS.

65.1 Linear congruential generator revisited


The pseudorandom number generator we considered earlier20 on page 323has a flaw: it’s not thread-safe, because it has
an internal state variable which can be read and/or modified in different threads simultaneously.

65.1.1 Win32.


UninitializedTLSdata

One solution is to add__declspec( thread )modifier to the global variable, then it will be allocated in theTLS(line
9):

1 #include <stdint.h>
2 #include <windows.h>
3 #include <winnt.h>
4
5 // from the Numerical Recipes book:
6 #define RNG_a 1664525
7 #define RNG_c 1013904223
8
9 __declspec( thread ) uint32_t rand_state;
10
11 void my_srand (uint32_t init)


(^1) C11 also has thread support, optional though

Free download pdf