Windows thread local storage bug

101 Views Asked by At

In Windows, a segment error occurs when an executable file accesses a thread local variable in the dynamic library in extern mode.This problem occurs when clang is used, but not when gcc is used.

// test.c
__thread int g_cnt = 1;

Compile the dynamic library:

clang --target=x86_64-pc-windows-gnu test.c -shared -o libtest.dll

// main.c
#include <stdio.h>

extern __thread int g_cnt;

int get_cnt()
{
    return g_cnt;
}

int main() {
    int cnt = get_cnt();
    printf("cnt = %d\n", cnt);


    return 0;
}

Generating an Executable File:

clang --target=x86_64-pc-windows-gnu main.c -L.\ -ltest -o main.exe

Segment error while accessing thread local variables

Thread 1 received signal SIGSEGV, Segmentation fault.
0x00007ff6bf5717e5 in get_cnt ()
(gdb) disassemble
Dump of assembler code for function get_cnt:
   0x00007ff6bf5717d0 <+0>:     mov    0xe8ea(%rip),%eax        # 0x7ff6bf5800c0 <_tls_index>
   0x00007ff6bf5717d6 <+6>:     mov    %eax,%ecx
   0x00007ff6bf5717d8 <+8>:     mov    %gs:0x58,%rax
   0x00007ff6bf5717e1 <+17>:    mov    (%rax,%rcx,8),%rax
=> 0x00007ff6bf5717e5 <+21>:    mov    0x7f5782f0(%rax),%eax
   0x00007ff6bf5717eb <+27>:    ret
   0x00007ff6bf5717ec <+28>:    nopl   0x0(%rax)
End of assembler dump.
(gdb) p *0x7ff6bf5800c0
$1 = 0

Is this a clang bug?

The version of clang I tested was 12.0.1

Mingw uses x86_64-posix-seh-gcc-12.1.0-mingw-w64msvcrt-10.0.0.

0

There are 0 best solutions below