简体   繁体   English

在Linux上,TLS是由内核还是由libc(或其他语言运行时)设置的?

[英]On Linux, is TLS set up by the kernel or by libc (or other language runtime)?

I'm just studying how TLS (thread-local storage) is implemented on Linux systems. 我只是在研究Linux系统上如何实现TLS(线程本地存储)。 The document ELF Handling for Thread-Local Storage explains how a program's requirements for thread-local variables can be encoded in an ELF binary, and how the "runtime" should handle such binaries. 用于线程本地存储的ELF处理 ”文档介绍了如何将程序对线程本地变量的要求编码为ELF二进制文件,以及“运行时”应如何处理此类二进制文件。

However, it's not clear to me whether in practice the "runtime" which sets up the TLS area(s) will be the Linux kernel (and its code for loading ELF binaries) or some initialization code in libc. 但是,我不清楚在实践中设置TLS区域的“运行时”是Linux内核(及其用于加载ELF二进制代码的代码)还是libc中的某些初始化代码。 Could someone explain briefly? 有人可以简要解释一下吗?

(Background: I'm trying to statically-link and run an application, but it segfaults on start. In gdb, I can see the segfaulting code is some init code from libc. It's trying to read a static variable using an address relative to GS, but GS is zero.) (背景:我正在尝试静态链接并运行应用程序,但启动时它会出现段错误。在gdb中,我可以看到段错误代码是libc的一些初始化代码。它正在尝试使用相对于地址的静态变量进行读取GS,但GS为零。)

Thread-local storage initialisation is part of the libc-provided start-up code. 线程本地存储初始化是libc提供的启动代码的一部分。 When statically linking, your linker should add the TLS initialisation to the start-up code linked into your program. 静态链接时,链接器应将TLS初始化添加到链接到程序的启动代码中。

For example, glibc has __libc_setup_tls and _dl_tls_setup (among other, related things) in libc.a , which will be added to the initialisation code of your program if you link via, say, gcc -static . 例如,glibc的有__libc_setup_tls_dl_tls_setup (除其他,相关的东西)中libc.a ,如果通过,也就是说,链接将被添加到您的程序的初始化代码gcc -static (For dynamically-linked programs the _dl_ ... functions are part of the ELF dynamic linker-loader, ld-linux.so , which isn't used to run a statically-linked program.) (对于动态链接的程序, _dl_ ...函数是ELF动态链接加载程序ld-linux.so ,它不用于运行静态链接的程序。)

Proper TLS initialisation in a statically-linked executable is, therefore, a result of collaboration between your C library (which provides the code) and your toolchain (which has to understand how to properly link in all the necessary start-up code). 因此,在静态链接的可执行文件中正确进行TLS初始化是C库(提供代码)和工具链(必须了解如何正确链接所有必要的启动代码)之间协作的结果。

The kernel's involvement in TLS initialisation is minor. 内核对TLS初始化的参与很小。 (Basically, it just has to ensure that the .tdata section is available to libc for initialisation.) See ELF file TLS and LOAD program sections for details. (基本上,只需要确保.tdata节可用于libc进行初始化。)有关详细信息,请参见ELF文件TLS和LOAD程序节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM