On Linux, is TLS configured by the kernel or libc (or another runtime language)?

I am just learning how TLS (streaming local storage) is implemented on Linux systems. The ELF Processing for Streaming Storage document explains how program requirements for local stream variables can be encoded in binary ELF format and how runtime should handle such binary files.

However, it’s not clear to me whether in practice the “runtime environment” that sets the TLS region (s) will be the Linux kernel (and its code for downloading ELF binaries) or some initialization code in libc. Can someone explain briefly?

(Background: I try to statically link and start the application, but it segfaults at startup. In gdb, I see that the segfaulting code is some init code from libc. It tries to read the static variable using the address relative to GS, but GS is zero.)

+7
c linux libc thread-local-storage
source share
1 answer

Initializing threads to local storage is part of the startup code provided by libc. With static binding, your linker should add TLS initialization to the startup code associated with your program.

For example, glibc has __libc_setup_tls and _dl_tls_setup (among other things, related things) in libc.a , which will be added to the initialization code of your program if you link, say, gcc -static . (For dynamically linked programs, the _dl_ ... functions are part of the ELF dynamic linker-loader, ld-linux.so , which is not used to run a statically linked program.)

Proper TLS initialization in a statically linked executable is the result of the collaboration of your C library (which provides the code) and your toolchain (which should understand how to properly link all the necessary launch codes).

Kernel involvement in TLS initialization is negligible. (Basically, you just need to make sure that the .tdata section is accessible to libc for initialization.) For more information, see TFS files and LOAD files of an ELF file .

+4
source share

All Articles