Assembly Language for Beginners

(Jeff_L) #1

6.2 Thread Local Storage


mov edx, DWORD PTR [rsp+12] ; reload value from the local stack and pass it to ⤦
Çprintf()
mov esi, OFFSET FLAT:.LC0 ; '%d'
mov edi, 1
xor eax, eax
call __printf_chk
add rsp, 24
ret

GCC for ARM64 does the same, but this space is calledRegister Save Areahere:


Listing 6.13: Optimizing GCC 4.9.1 ARM64

f:
stp x29, x30, [sp, -32]!
add x29, sp, 0 ; setup FP
add x1, x29, 32 ; calculate address of variable in Register Save Area
str w0, [x1,-4]! ; store input value there
mov x0, x1 ; pass address of variable to the modify_a()
bl modify_a
ldr w1, [x29,28] ; load value from the variable and pass it to printf()
adrp x0, .LC0 ; '%d'
add x0, x0, :lo12:.LC0
bl printf ; call printf()
ldp x29, x30, [sp], 32
ret
.LC0:
.string "%d\n"


By the way, a similar usage of theShadow Spaceis also considered here:3.14.1 on page 520.


6.2 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.


Multiplethreadsmaysimultaneouslycallfunctionswhichreturnanerrorcodeinerrno, soaglobalvariable
will not work correctly here for multi-threaded programs, soerrnomust be stored in theTLS.


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


Listing 6.14: C++11

#include
#include


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, thetmpvariable is to be allocated in the section
devoted to theTLS.


6.2.1 Linear congruential generator revisited


The pseudorandom number generator we considered earlier1.23 on page 338has 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.


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

Free download pdf