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