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+ but it should pass with Bionic
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: arm,powerpc,i386-linux && !android
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   // Clear any previous errors. On Android, the dynamic loader can have some
27   // left over dlerror() messages due to a missing symbol resolution for a
28   // deprecated malloc function.
29   dlerror();
30 
31   void *handle = dlopen(path.c_str(), RTLD_LAZY);
32   assert(handle != 0);
33   typedef void **(* store_t)(void *p);
34   store_t StoreToTLS = (store_t)dlsym(handle, "StoreToTLS");
35 
36   // Sometimes dlerror() occurs when we broke the interceptors.
37   // Add the message here to make the error more obvious.
38   const char *dlerror_msg = dlerror();
39   if (dlerror_msg != nullptr) {
40     fprintf(stderr, "DLERROR: %s\n", dlerror_msg);
41     fflush(stderr);
42     abort();
43   }
44   void *p = malloc(1337);
45   // If we don't  know about dynamic TLS, we will return a false leak above.
46   void **p_in_tls = StoreToTLS(p);
47   assert(*p_in_tls == p);
48   print_address("Test alloc: ", 1, p);
49   return 0;
50 }
51 // CHECK: Test alloc: [[ADDR:0x[0-9,a-f]+]]
52 // CHECK: LeakSanitizer: detected memory leaks
53 // CHECK: [[ADDR]] (1337 bytes)
54 // CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer:
55 
56 #else  // BUILD_DSO
57 // A loadable module with a large thread local section, which would require
58 // allocation of a new TLS storage chunk when loaded with dlopen(). We use it
59 // to test the reachability of such chunks in LSan tests.
60 
61 // This must be large enough that it doesn't fit into preallocated static TLS
62 // space (see STATIC_TLS_SURPLUS in glibc).
63 __thread void *huge_thread_local_array[(1 << 20) / sizeof(void *)];
64 
65 extern "C" void **StoreToTLS(void *p) {
66   huge_thread_local_array[0] = p;
67   return &huge_thread_local_array[0];
68 }
69 #endif  // BUILD_DSO
70