LD_PRELOAD and local stream variable

I have a shared library (libtest.cpp) and a simple program (test.cpp). I want them to share the local gVar stream variable . The shared library is linked through LD_PRELOAD.

Here is my code for the libtest.cpp shared library:

#include<stdio.h> __thread int gVar; void print_gVar(){ printf("%d\n", gVar); } 

Below is the code for 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 gVar in libtest.cpp. However, I only got 0. It seems that gVar in libtest.cpp and gVar in test.cpp are not related.

I did some additional tests:

If I add __attribute__((weak)) to the gVar in any of the files, the output will be 0.

If I delete __thread from both files, then the result will be 10 (successful).

If I add extern and __attribute__((weak)) to the gVar in libtest.cpp, a segmentation error will occur.

I think __thread should be something wrong with LD_PRELOAD and __thread . But I can’t understand.

Can someone tell me how can I make it work? Thank you very much!

+6
source share
1 answer

This is not possible because thread-local storage requires thread initialization.

LD_PRELOAD load the library before loading the standard library, which will ruin the initialization of TLS.

Update:

Read Sections 2 and 3 ELF Processing for Local Storage

+5
source

All Articles