1 // RUN: %clangxx_tsan -O1 %s -DBUILD_SO -fPIC -shared -o %t-so.so 2 // RUN: %clangxx_tsan -O1 %s %link_libcxx_tsan -o %t && %run %t 2>&1 | FileCheck %s 3 4 // A test for loading a dynamic library with static TLS. 5 // Such static TLS is a hack that allows a dynamic library to have faster TLS, 6 // but it can be loaded only iff all threads happened to allocate some excess 7 // of static TLS space for whatever reason. If it's not the case loading fails with: 8 // dlopen: cannot load any more object with static TLS 9 // We used to produce a false positive because dlopen will write into TLS 10 // of all existing threads to initialize/zero TLS region for the loaded library. 11 // And this appears to be racing with initialization of TLS in the thread 12 // since we model a write into the whole static TLS region (we don't know what part 13 // of it is currently unused): 14 // WARNING: ThreadSanitizer: data race (pid=2317365) 15 // Write of size 1 at 0x7f1fa9bfcdd7 by main thread: 16 // #0 memset 17 // #1 init_one_static_tls 18 // #2 __pthread_init_static_tls 19 // [[ this is where main calls dlopen ]] 20 // #3 main 21 // Previous write of size 8 at 0x7f1fa9bfcdd0 by thread T1: 22 // #0 __tsan_tls_initialization 23 24 // Failing on bots: https://lab.llvm.org/buildbot#builders/184/builds/1580 25 // UNSUPPORTED: aarch64 26 27 #ifdef BUILD_SO 28 29 __attribute__((tls_model("initial-exec"))) __thread char x = 42; 30 __attribute__((tls_model("initial-exec"))) __thread char y; 31 32 extern "C" int sofunc() { return ++x + ++y; } 33 34 #else // BUILD_SO 35 36 # include "../test.h" 37 # include <dlfcn.h> 38 # include <string> 39 40 __thread int x[1023]; 41 42 void *lib; 43 void (*func)(); 44 int ready; 45 46 void *thread(void *arg) { 47 barrier_wait(&barrier); 48 if (__atomic_load_n(&ready, __ATOMIC_ACQUIRE)) 49 func(); 50 if (dlclose(lib)) { 51 printf("error in dlclose: %s\n", dlerror()); 52 exit(1); 53 } 54 return 0; 55 } 56 57 int main(int argc, char *argv[]) { 58 barrier_init(&barrier, 2); 59 pthread_t th; 60 pthread_create(&th, 0, thread, 0); 61 lib = dlopen((std::string(argv[0]) + "-so.so").c_str(), RTLD_NOW); 62 if (lib == 0) { 63 printf("error in dlopen: %s\n", dlerror()); 64 return 1; 65 } 66 func = (void (*)())dlsym(lib, "sofunc"); 67 if (func == 0) { 68 printf("error in dlsym: %s\n", dlerror()); 69 return 1; 70 } 71 __atomic_store_n(&ready, 1, __ATOMIC_RELEASE); 72 barrier_wait(&barrier); 73 func(); 74 pthread_join(th, 0); 75 fprintf(stderr, "DONE\n"); 76 return 0; 77 } 78 79 #endif // BUILD_SO 80 81 // CHECK: DONE 82