Program Startup
At program startup, the runtime system creates TLS for the main thread.
First, the runtime linker logically combines the
TLS templates for all loaded dynamic
objects, into a single static
template. Each dynamic object's TLS template is
assigned an offset within the combined template,
tlsoffset
m, as
follows.
-
tlsoffset
1= round(tlssize
1, align
1)
-
tlsoffset
m+1= round(tlsoffset
m+ tlssize
m+1, align
m+1)
tlssize
m+1 and
align
m+1 are the
size and alignment, respectively, for the allocation template for
dynamic object m
. Where 1 <= m <=
M
, and M
is the total number of
loaded dynamic objects. The round(offset, align)
function returns an offset rounded up to the next multiple of
align.
Next, the runtime linker computes the allocation size that is required
for the startup TLS,
tlssize
S. This
size is equal to
tlsoffset
M, plus
an additional 512
bytes. This addition provides a
backup reservation for static TLS references.
Shared objects that make static TLS references, and are loaded after
process initialization, are assigned to this backup reservation.
However, this reservation is a fixed, limited size. In addition,
this reservation is only capable of providing storage for
uninitialized TLS data items. For maximum
flexibility, shared objects should reference thread-local variables
using a dynamic TLS model.
The static TLS arena associated with the calculated
TLS size
tlssize
S, is
placed immediately preceding the thread pointer
tp
t. Accesses to
this TLS data is based off of subtractions from
tp
t.
The static TLS arena is associated with a linked list of initialization records. Each record in this list describes the TLS initialization image for one loaded dynamic object. Each record contains the following fields.
-
A pointer to the TLS initialization image.
-
The size of the TLS initialization image.
-
The
tlsoffset
m of the object. -
A flag indicating whether the object uses a static TLS model.
The thread library uses this information to allocate storage for the initial thread. This storage is initialized, and a dynamic TLS vector for the initial thread is created.