https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80258
Bug ID: 80258
Summary: On x86_64 with -fPIC, accesses to TLS can see the
wrong thread's TLS
Product: gcc
Version: unknown
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: ipa
Assignee: unassigned at gcc dot gnu.org
Reporter: tmyklebu at gmail dot com
Target Milestone: ---
The address of the running thread's TLS appears to be loaded only once although
the running thread may change.
This simple example:
__thread int foo;
void something();
void f() {
foo = 1;
something();
foo = 2;
}
when built with -fPIC -O3, begets this code, where %fs:0x0 is loaded only once:
0000000000000760 <f>:
760: 53 push %rbx
761: 64 48 8b 04 25 00 00 mov %fs:0x0,%rax
768: 00 00
76a: 48 8d 80 fc ff ff ff lea -0x4(%rax),%rax
771: 48 89 c3 mov %rax,%rbx
774: c7 00 01 00 00 00 movl $0x1,(%rax)
77a: 31 c0 xor %eax,%eax
77c: e8 cf ff ff ff callq 750 <something>
781: c7 03 02 00 00 00 movl $0x2,(%rbx)
787: 5b pop %rbx
788: c3 retq
789: 0f 1f 80 00 00 00 00 nopl 0x0(%rax)
The function called something could play around with the functions from
ucontext.h, meaning the value of %fs could change during that call. The
attached program is a self-contained program reproducing the bug on my Linux
machine. I get output like
5415 :(
5416 :)
if I pass at most one of '-fPIC' and '-O3'. If I build the program like this:
gcc -pthread -O3 -fPIC -o foo255 foo255.c
and run, then I get the following output, which has two sad faces:
5448 :(
5449 :(
I used the following compiler:
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/6/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Debian 6.3.0-10'
--with-bugurl=file:///usr/share/doc/gcc-6/README.Bugs
--enable-languages=c,ada,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr
--program-suffix=-6 --program-prefix=x86_64-linux-gnu- --enable-shared
--enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext
--enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/
--enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes
--with-default-libstdcxx-abi=new --enable-gnu-unique-object
--disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie
--with-system-zlib --disable-browser-plugin --enable-java-awt=gtk
--enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-6-amd64/jre
--enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-6-amd64
--with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-6-amd64
--with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar
--with-target-system-zlib --enable-objc-gc=auto --enable-multiarch
--with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32
--enable-multilib --with-tune=generic --enable-checking=release
--build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 6.3.0 20170321 (Debian 6.3.0-10)