| 1 | // RUN: %clang_tsan %darwin_min_target_with_tls_support %s -o %t |
| 2 | // RUN: %clang_tsan %darwin_min_target_with_tls_support %s -DBUILD_SO -fPIC -o \ |
| 3 | // RUN: %t-so.so -shared |
| 4 | // RUN: %run %t 2>&1 | FileCheck %s |
| 5 | // XFAIL: target={{.*netbsd.*}} |
| 6 | |
| 7 | // Test that tsan cleans up dynamic TLS memory between reuse. |
| 8 | |
| 9 | #include "test.h" |
| 10 | |
| 11 | #ifndef BUILD_SO |
| 12 | #include <assert.h> |
| 13 | #include <dlfcn.h> |
| 14 | |
| 15 | typedef volatile long *(* get_t)(); |
| 16 | get_t GetTls; |
| 17 | |
| 18 | void *Thread1(void *arg) { |
| 19 | pthread_detach(th: pthread_self()); |
| 20 | volatile long *x = GetTls(); |
| 21 | *x = 42; |
| 22 | fprintf(stderr, format: "stack: %p dtls: %p\n" , &x, x); |
| 23 | barrier_wait(barrier: &barrier); |
| 24 | return 0; |
| 25 | } |
| 26 | |
| 27 | void *Thread2(void *arg) { |
| 28 | volatile long *x = GetTls(); |
| 29 | *x = 42; |
| 30 | fprintf(stderr, format: "stack: %p dtls: %p\n" , &x, x); |
| 31 | return 0; |
| 32 | } |
| 33 | |
| 34 | int main(int argc, char *argv[]) { |
| 35 | char path[4096]; |
| 36 | snprintf(s: path, maxlen: sizeof(path), format: "%s-so.so" , argv[0]); |
| 37 | |
| 38 | void *handle = dlopen(file: path, RTLD_LAZY); |
| 39 | if (!handle) fprintf(stderr, format: "%s\n" , dlerror()); |
| 40 | assert(handle != 0); |
| 41 | GetTls = (get_t)dlsym(handle: handle, name: "GetTls" ); |
| 42 | assert(dlerror() == 0); |
| 43 | |
| 44 | barrier_init(barrier: &barrier, count: 2); |
| 45 | pthread_t t[2]; |
| 46 | pthread_create(newthread: &t[0], attr: 0, start_routine: Thread1, arg: 0); |
| 47 | barrier_wait(barrier: &barrier); |
| 48 | // Wait for actual thread termination without using pthread_join, |
| 49 | // which would synchronize threads. |
| 50 | sleep(seconds: 1); |
| 51 | pthread_create(newthread: &t[1], attr: 0, start_routine: Thread2, arg: 0); |
| 52 | pthread_join(th: t[1], thread_return: 0); |
| 53 | fprintf(stderr, format: "DONE\n" ); |
| 54 | return 0; |
| 55 | } |
| 56 | #else // BUILD_SO |
| 57 | __thread long huge_thread_local_array[1 << 17]; |
| 58 | long *GetTls() { |
| 59 | return &huge_thread_local_array[0]; |
| 60 | } |
| 61 | #endif |
| 62 | |
| 63 | // CHECK-NOT: ThreadSanitizer: data race |
| 64 | // CHECK: DONE |
| 65 | |