1 // Test that lsan handles tls correctly for many threads 2 // RUN: LSAN_BASE="report_objects=1:use_stacks=0:use_registers=0" 3 // RUN: %clangxx_lsan %s -o %t 4 // RUN: %env_lsan_opts=$LSAN_BASE:"use_tls=0" not %run %t 2>&1 | FileCheck %s 5 // RUN: %env_lsan_opts=$LSAN_BASE:"use_tls=1" %run %t 2>&1 6 // RUN: %env_lsan_opts="" %run %t 2>&1 7 8 // On glibc, this requires the range returned by GetTLS to include 9 // specific_1stblock and specific in `struct pthread`. 10 // UNSUPPORTED: arm-linux, armhf-linux 11 12 // TSD on NetBSD does not use TLS 13 // UNSUPPORTED: netbsd 14 15 #include <assert.h> 16 #include <limits.h> 17 #include <pthread.h> 18 #include <stdlib.h> 19 #include <unistd.h> 20 21 static const int NUM_THREADS = 10; 22 23 pthread_cond_t cond = PTHREAD_COND_INITIALIZER; 24 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 25 int finished = 0; 26 27 // We won't be able to create the maximum number of keys, due to other users 28 // of the tls, but we'll use as many keys as we can before failing to create 29 // a new key. 30 pthread_key_t keys[PTHREAD_KEYS_MAX]; 31 static const int PTHREAD_KEY_INVALID = 0xffffffff; 32 33 void alloc() { 34 for (int i = 0; i < PTHREAD_KEYS_MAX; ++i) { 35 void *ptr = malloc(123); 36 if ((keys[i] == PTHREAD_KEY_INVALID) || pthread_setspecific(keys[i], ptr)) { 37 free(ptr); 38 break; 39 } 40 } 41 } 42 43 void pthread_destructor(void *arg) { 44 assert(0 && "pthread destructors shouldn't be called"); 45 } 46 47 void *thread_start(void *arg) { 48 alloc(); 49 50 pthread_mutex_lock(&mutex); 51 finished++; 52 pthread_mutex_unlock(&mutex); 53 54 // don't exit, to intentionally leak tls data 55 while (1) 56 sleep(100); 57 } 58 59 int main() { 60 for (int i = 0; i < PTHREAD_KEYS_MAX; ++i) { 61 if (pthread_key_create(&keys[i], pthread_destructor)) { 62 keys[i] = PTHREAD_KEY_INVALID; 63 break; 64 } 65 } 66 67 pthread_t thread[NUM_THREADS]; 68 for (int i = 0; i < NUM_THREADS; ++i) { 69 assert(0 == pthread_create(&thread[i], 0, thread_start, 0)); 70 } 71 // spin until all threads have finished 72 while (finished < NUM_THREADS) 73 sleep(1); 74 exit(0); 75 } 76 77 // CHECK: LeakSanitizer: detected memory leaks 78 // CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer: 79