1 // Test that dynamically allocated TLS space is included in the root set.
2 // RUN: LSAN_BASE="report_objects=1:use_stacks=0:use_registers=0"
3 // RUN: %clangxx %s -DBUILD_DSO -fPIC -shared -o %t-so.so
4 // RUN: %clangxx_lsan %s -o %t
5 // RUN: LSAN_OPTIONS=$LSAN_BASE:"use_tls=0" not %run %t 2>&1 | FileCheck %s
6 // RUN: LSAN_OPTIONS=$LSAN_BASE:"use_tls=1" %run %t 2>&1
7 // RUN: LSAN_OPTIONS="" %run %t 2>&1
8 
9 #ifndef BUILD_DSO
10 #include <assert.h>
11 #include <dlfcn.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string>
15 
main(int argc,char * argv[])16 int main(int argc, char *argv[]) {
17   std::string path = std::string(argv[0]) + "-so.so";
18 
19   void *handle = dlopen(path.c_str(), RTLD_LAZY);
20   assert(handle != 0);
21   typedef void **(* store_t)(void *p);
22   store_t StoreToTLS = (store_t)dlsym(handle, "StoreToTLS");
23   assert(dlerror() == 0);
24 
25   void *p = malloc(1337);
26   // If we don't  know about dynamic TLS, we will return a false leak above.
27   void **p_in_tls = StoreToTLS(p);
28   assert(*p_in_tls == p);
29   fprintf(stderr, "Test alloc: %p.\n", p);
30   return 0;
31 }
32 // CHECK: Test alloc: [[ADDR:.*]].
33 // CHECK: LeakSanitizer: detected memory leaks
34 // CHECK: [[ADDR]] (1337 bytes)
35 // CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer:
36 
37 #else  // BUILD_DSO
38 // A loadable module with a large thread local section, which would require
39 // allocation of a new TLS storage chunk when loaded with dlopen(). We use it
40 // to test the reachability of such chunks in LSan tests.
41 
42 // This must be large enough that it doesn't fit into preallocated static TLS
43 // space (see STATIC_TLS_SURPLUS in glibc).
44 __thread void *huge_thread_local_array[(1 << 20) / sizeof(void *)]; // NOLINT
45 
StoreToTLS(void * p)46 extern "C" void **StoreToTLS(void *p) {
47   huge_thread_local_array[0] = p;
48   return &huge_thread_local_array[0];
49 }
50 #endif  // BUILD_DSO
51