[英]LD_PRELOAD and thread local variable
I have a shared library (libtest.cpp) and a simple program (test.cpp). 我有一个共享库(libtest.cpp)和一个简单的程序(test.cpp)。 I want them to share a thread local variable gVar .
我希望他们共享一个线程局部变量gVar 。 The shared library is linked through LD_PRELOAD.
共享库通过LD_PRELOAD链接。
Here is my code for the shared library libtest.cpp: 这是我的共享库libtest.cpp的代码:
#include<stdio.h>
__thread int gVar;
void print_gVar(){
printf("%d\n", gVar);
}
Below is the code for test.cpp. 下面是test.cpp的代码。
#include<stdio.h>
__thread int gVar;
void __attribute__((weak)) print_gVar();
int main(){
gVar = 10;
print_gVar();
return 0;
}
And I use the following script to compile and run them. 我使用以下脚本来编译和运行它们。
g++ -g -shared -fPIC -olibtest.so libtest.cpp
g++ -g -fPIC -o test test.cpp
LD_PRELOAD=./libtest.so ./test
The expected result is 10 because the assignment in test.cpp will affect the gVar in libtest.cpp. 预期的结果是10,因为test.cpp中的赋值将影响libtest.cpp中的gVar。 However, I only got 0. It seems that the the gVar in libtest.cpp and the gVar in test.cpp are not linked.
但是,我只得到0.似乎libtest.cpp中的gVar和test.cpp中的gVar没有链接。
I did some additional tests: 我做了一些额外的测试:
If I add __attribute__((weak))
to the declaration of gVar
in any of the files, the output is still 0. 如果我将
__attribute__((weak))
到任何文件中的gVar
声明中,则输出仍为0。
If I remove __thread
from both files, then the result is 10 (successful). 如果我从两个文件中删除
__thread
,则结果为10(成功)。
If I add extern
and __attribute__((weak))
to the declaration of gVar
in libtest.cpp, there will be segmentation fault. 如果我将
gVar
中的extern
和__attribute__((weak))
添加到gVar
的声明中,则会出现分段错误。
I guess there must be something wrong with LD_PRELOAD
and __thread
. 我想
LD_PRELOAD
和__thread
一定有问题。 But I cannot figure out. 但我无法弄清楚。
Could anyone tell me how I can make it work? 谁能告诉我如何让它发挥作用? Thank you very much!
非常感谢你!
This is not possible, since thread-local-storage requires per-thread initialisation. 这是不可能的,因为线程本地存储需要每线程初始化。
LD_PRELOAD
will load the library even before the standard library is loaded, which messes up TLS initialisation. LD_PRELOAD
甚至会在加载标准库之前加载库,这会混淆TLS初始化。
Update: 更新:
Please read sections 2 and 3 of ELF Handling For Thread-Local Storage 请阅读ELF处理线程局部存储的第2节和第3节
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.