• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *  * Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *  * Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in
12  *    the documentation and/or other materials provided with the
13  *    distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <dlfcn.h>
30 #include <link.h>
31 
32 #include <android-base/file.h>
33 #include <gtest/gtest.h>
34 
35 #include <thread>
36 
37 #include "gtest_globals.h"
38 #include "platform/bionic/tls.h"
39 #include "utils.h"
40 
41 #if defined(__BIONIC__)
42 #include "bionic/pthread_internal.h"
43 #endif
44 
45 // Access libtest_elftls_shared_var.so's TLS variable using an IE access.
46 __attribute__((tls_model("initial-exec"))) extern "C" __thread int elftls_shared_var;
47 
TEST(elftls_dl,dlopen_shared_var_ie)48 TEST(elftls_dl, dlopen_shared_var_ie) {
49   // libtest_elftls_shared_var_ie.so can be dlopen'ed, even though it contains a
50   // TLS IE access, because its IE access references a TLS variable from
51   // libtest_elftls_shared_var.so, which is DT_NEEDED by the executable. This
52   // pattern appears in sanitizers, which use TLS IE instrumentation in shared
53   // objects to access special variables exported from the executable or from a
54   // preloaded solib.
55   void* lib = dlopen("libtest_elftls_shared_var_ie.so", RTLD_LOCAL | RTLD_NOW);
56   ASSERT_NE(nullptr, lib);
57 
58   auto bump_shared_var = reinterpret_cast<int(*)()>(dlsym(lib, "bump_shared_var"));
59   ASSERT_NE(nullptr, bump_shared_var);
60 
61   ASSERT_EQ(21, ++elftls_shared_var);
62   ASSERT_EQ(22, bump_shared_var());
63 
64   std::thread([bump_shared_var] {
65     ASSERT_EQ(21, ++elftls_shared_var);
66     ASSERT_EQ(22, bump_shared_var());
67   }).join();
68 }
69 
TEST(elftls_dl,dlopen_ie_error)70 TEST(elftls_dl, dlopen_ie_error) {
71   std::string helper = GetTestlibRoot() + "/elftls_dlopen_ie_error_helper";
72   std::string src_path = GetTestlibRoot() + "/libtest_elftls_shared_var_ie.so";
73   std::string dst_path = GetTestlibRoot() + "/libtest_elftls_shared_var.so";
74 #if defined(__BIONIC__)
75   std::string error =
76       "dlerror: dlopen failed: TLS symbol \"elftls_shared_var\" in dlopened \"" + dst_path + "\" " +
77       "referenced from \"" + src_path + "\" using IE access model\n";
78 #else
79   // glibc will reserve some surplus static TLS memory, allowing this test to pass.
80   std::string error = "success\n";
81 #endif
82 
83   chmod(helper.c_str(), 0755); // TODO: "x" lost in CTS, b/34945607
84   ExecTestHelper eth;
85   eth.SetArgs({ helper.c_str(), nullptr });
86   eth.Run([&]() { execve(helper.c_str(), eth.GetArgs(), eth.GetEnv()); }, 0, error.c_str());
87 }
88 
89 // Use a GD access (__tls_get_addr or TLSDESC) to modify a variable in static
90 // TLS memory.
TEST(elftls_dl,access_static_tls)91 TEST(elftls_dl, access_static_tls) {
92   void* lib = dlopen("libtest_elftls_dynamic.so", RTLD_LOCAL | RTLD_NOW);
93   ASSERT_NE(nullptr, lib);
94 
95   auto bump_shared_var = reinterpret_cast<int(*)()>(dlsym(lib, "bump_shared_var"));
96   ASSERT_NE(nullptr, bump_shared_var);
97 
98   ASSERT_EQ(21, ++elftls_shared_var);
99   ASSERT_EQ(22, bump_shared_var());
100 
101   std::thread([bump_shared_var] {
102     ASSERT_EQ(21, ++elftls_shared_var);
103     ASSERT_EQ(22, bump_shared_var());
104   }).join();
105 }
106 
TEST(elftls_dl,bump_local_vars)107 TEST(elftls_dl, bump_local_vars) {
108   void* lib = dlopen("libtest_elftls_dynamic.so", RTLD_LOCAL | RTLD_NOW);
109   ASSERT_NE(nullptr, lib);
110 
111   auto bump_local_vars = reinterpret_cast<int(*)()>(dlsym(lib, "bump_local_vars"));
112   ASSERT_NE(nullptr, bump_local_vars);
113 
114   ASSERT_EQ(42, bump_local_vars());
115   std::thread([bump_local_vars] {
116     ASSERT_EQ(42, bump_local_vars());
117   }).join();
118 }
119 
120 extern "C" int* missing_weak_tls_addr();
121 
122 // The Bionic linker resolves a TPREL relocation to an unresolved weak TLS
123 // symbol to 0, which is added to the thread pointer. N.B.: A TPREL relocation
124 // in a static executable is resolved by the static linker instead, and static
125 // linker behavior varies (especially with bfd and gold). See
126 // https://bugs.llvm.org/show_bug.cgi?id=40570.
TEST(elftls_dl,tprel_missing_weak)127 TEST(elftls_dl, tprel_missing_weak) {
128   ASSERT_EQ(static_cast<void*>(__get_tls()), missing_weak_tls_addr());
129   std::thread([] {
130     ASSERT_EQ(static_cast<void*>(__get_tls()), missing_weak_tls_addr());
131   }).join();
132 }
133 
134 // The behavior of accessing an unresolved weak TLS symbol using a dynamic TLS
135 // relocation depends on which kind of implementation the target uses. With
136 // TLSDESC, the result is NULL. With __tls_get_addr, the result is the
137 // generation count (or maybe undefined behavior)? This test only tests TLSDESC.
TEST(elftls_dl,tlsdesc_missing_weak)138 TEST(elftls_dl, tlsdesc_missing_weak) {
139 #if defined(__aarch64__)
140   void* lib = dlopen("libtest_elftls_dynamic.so", RTLD_LOCAL | RTLD_NOW);
141   ASSERT_NE(nullptr, lib);
142 
143   auto missing_weak_dyn_tls_addr = reinterpret_cast<int*(*)()>(dlsym(lib, "missing_weak_dyn_tls_addr"));
144   ASSERT_NE(nullptr, missing_weak_dyn_tls_addr);
145 
146   ASSERT_EQ(nullptr, missing_weak_dyn_tls_addr());
147   std::thread([missing_weak_dyn_tls_addr] {
148     ASSERT_EQ(nullptr, missing_weak_dyn_tls_addr());
149   }).join();
150 #else
151   GTEST_SKIP() << "This test is only run on TLSDESC-based targets";
152 #endif
153 }
154 
TEST(elftls_dl,dtv_resize)155 TEST(elftls_dl, dtv_resize) {
156 #if defined(__BIONIC__)
157 #define LOAD_LIB(soname) ({                           \
158     auto lib = dlopen(soname, RTLD_LOCAL | RTLD_NOW); \
159     ASSERT_NE(nullptr, lib);                          \
160     reinterpret_cast<int(*)()>(dlsym(lib, "bump"));   \
161   })
162 
163   auto dtv = []() -> TlsDtv* { return __get_tcb_dtv(__get_bionic_tcb()); };
164 
165   static_assert(sizeof(TlsDtv) == 3 * sizeof(void*),
166                 "This test assumes that the Dtv has a 3-word header");
167 
168   // Initially there are 4 modules:
169   //  - the main test executable
170   //  - libc
171   //  - libtest_elftls_shared_var
172   //  - libtest_elftls_tprel
173 
174   // The initial DTV is an empty DTV with no generation and a size of 0.
175   TlsDtv* zero_dtv = dtv();
176   ASSERT_EQ(0u, zero_dtv->count);
177   ASSERT_EQ(nullptr, zero_dtv->next);
178   ASSERT_EQ(kTlsGenerationNone, zero_dtv->generation);
179 
180   // Load the fifth module.
181   auto func1 = LOAD_LIB("libtest_elftls_dynamic_filler_1.so");
182   ASSERT_EQ(101, func1());
183 
184   // After loading one module, the DTV should be initialized to the next
185   // power-of-2 size (including the header).
186   TlsDtv* initial_dtv = dtv();
187   ASSERT_EQ(5u, initial_dtv->count);
188   ASSERT_EQ(zero_dtv, initial_dtv->next);
189   ASSERT_LT(0u, initial_dtv->generation);
190 
191   // Load module 6.
192   auto func2 = LOAD_LIB("libtest_elftls_dynamic_filler_2.so");
193   ASSERT_EQ(102, func1());
194 
195 #if defined(__aarch64__)
196   // The arm64 TLSDESC resolver doesn't update the DTV if it is new enough for
197   // the given access.
198   ASSERT_EQ(5u, dtv()->count);
199 #else
200   // __tls_get_addr updates the DTV anytime the generation counter changes.
201   ASSERT_EQ(13u, dtv()->count);
202 #endif
203 
204   ASSERT_EQ(201, func2());
205   TlsDtv* new_dtv = dtv();
206   ASSERT_NE(initial_dtv, new_dtv);
207   ASSERT_EQ(initial_dtv, new_dtv->next);
208   ASSERT_EQ(13u, new_dtv->count);
209 
210   // Load module 7.
211   auto func3 = LOAD_LIB("libtest_elftls_dynamic_filler_3.so");
212   ASSERT_EQ(103, func1());
213   ASSERT_EQ(202, func2());
214   ASSERT_EQ(301, func3());
215 
216   ASSERT_EQ(new_dtv, dtv());
217 
218 #undef LOAD_LIB
219 #else
220   GTEST_SKIP() << "test doesn't apply to glibc";
221 #endif
222 }
223 
224 // Verify that variables are reset to their initial values after the library
225 // containing them is closed.
TEST(elftls_dl,dlclose_resets_values)226 TEST(elftls_dl, dlclose_resets_values) {
227   for (int round = 0; round < 2; ++round) {
228     void* lib = dlopen("libtest_elftls_dynamic.so", RTLD_LOCAL | RTLD_NOW);
229     ASSERT_NE(nullptr, lib);
230 
231     auto bump_local_vars = reinterpret_cast<int(*)()>(dlsym(lib, "bump_local_vars"));
232     ASSERT_NE(nullptr, bump_local_vars);
233 
234     ASSERT_EQ(42, bump_local_vars());
235     ASSERT_EQ(44, bump_local_vars());
236 
237     ASSERT_EQ(0, dlclose(lib));
238   }
239 }
240 
241 // Calling dlclose should remove the entry for the solib from the global list of
242 // ELF TLS modules. Test that repeatedly loading and unloading a library doesn't
243 // increase the DTV size.
TEST(elftls_dl,dlclose_removes_entry)244 TEST(elftls_dl, dlclose_removes_entry) {
245 #if defined(__BIONIC__)
246   auto dtv = []() -> TlsDtv* { return __get_tcb_dtv(__get_bionic_tcb()); };
247 
248   bool first = true;
249   size_t count = 0;
250 
251   // Use a large number of rounds in case the DTV is initially larger than
252   // expected.
253   for (int round = 0; round < 32; ++round) {
254     void* lib = dlopen("libtest_elftls_dynamic.so", RTLD_LOCAL | RTLD_NOW);
255     ASSERT_NE(nullptr, lib);
256 
257     auto bump_local_vars = reinterpret_cast<int(*)()>(dlsym(lib, "bump_local_vars"));
258     ASSERT_NE(nullptr, bump_local_vars);
259 
260     ASSERT_EQ(42, bump_local_vars());
261     if (first) {
262       first = false;
263       count = dtv()->count;
264     } else {
265       ASSERT_EQ(count, dtv()->count);
266     }
267 
268     dlclose(lib);
269   }
270 #else
271   GTEST_SKIP() << "test doesn't apply to glibc";
272 #endif
273 }
274 
275 // Use dlsym to get the address of a TLS variable in static TLS and compare it
276 // against the ordinary address of the variable.
TEST(elftls_dl,dlsym_static_tls)277 TEST(elftls_dl, dlsym_static_tls) {
278   void* lib = dlopen("libtest_elftls_shared_var.so", RTLD_LOCAL | RTLD_NOW);
279   ASSERT_NE(nullptr, lib);
280 
281   int* var_addr = static_cast<int*>(dlsym(lib, "elftls_shared_var"));
282   ASSERT_EQ(&elftls_shared_var, var_addr);
283 
284   std::thread([lib] {
285     int* var_addr = static_cast<int*>(dlsym(lib, "elftls_shared_var"));
286     ASSERT_EQ(&elftls_shared_var, var_addr);
287   }).join();
288 }
289 
290 // Use dlsym to get the address of a TLS variable in dynamic TLS and compare it
291 // against the ordinary address of the variable.
TEST(elftls_dl,dlsym_dynamic_tls)292 TEST(elftls_dl, dlsym_dynamic_tls) {
293   void* lib = dlopen("libtest_elftls_dynamic.so", RTLD_LOCAL | RTLD_NOW);
294   ASSERT_NE(nullptr, lib);
295   auto get_var_addr = reinterpret_cast<int*(*)()>(dlsym(lib, "get_large_tls_var_addr"));
296   ASSERT_NE(nullptr, get_var_addr);
297 
298   int* var_addr = static_cast<int*>(dlsym(lib, "large_tls_var"));
299   ASSERT_EQ(get_var_addr(), var_addr);
300 
301   std::thread([lib, get_var_addr] {
302     int* var_addr = static_cast<int*>(dlsym(lib, "large_tls_var"));
303     ASSERT_EQ(get_var_addr(), var_addr);
304   }).join();
305 }
306 
307 // Calling dladdr on a TLS variable's address doesn't find anything.
TEST(elftls_dl,dladdr_on_tls_var)308 TEST(elftls_dl, dladdr_on_tls_var) {
309   Dl_info info;
310 
311   // Static TLS variable
312   ASSERT_EQ(0, dladdr(&elftls_shared_var, &info));
313 
314   // Dynamic TLS variable
315   void* lib = dlopen("libtest_elftls_dynamic.so", RTLD_LOCAL | RTLD_NOW);
316   ASSERT_NE(nullptr, lib);
317   int* var_addr = static_cast<int*>(dlsym(lib, "large_tls_var"));
318   ASSERT_EQ(0, dladdr(var_addr, &info));
319 }
320 
321 // Verify that dladdr does not misinterpret a TLS symbol's value as a virtual
322 // address.
TEST(elftls_dl,dladdr_skip_tls_symbol)323 TEST(elftls_dl, dladdr_skip_tls_symbol) {
324   void* lib = dlopen("libtest_elftls_dynamic.so", RTLD_LOCAL | RTLD_NOW);
325 
326   auto get_local_addr = reinterpret_cast<void*(*)()>(dlsym(lib, "get_local_addr"));
327   ASSERT_NE(nullptr, get_local_addr);
328   void* local_addr = get_local_addr();
329 
330   Dl_info info;
331   ASSERT_NE(0, dladdr(local_addr, &info));
332 
333   std::string libpath = GetTestlibRoot() + "/libtest_elftls_dynamic.so";
334   char dli_realpath[PATH_MAX];
335   ASSERT_TRUE(realpath(info.dli_fname, dli_realpath));
336   ASSERT_STREQ(libpath.c_str(), dli_realpath);
337   ASSERT_STREQ(nullptr, info.dli_sname);
338   ASSERT_EQ(nullptr, info.dli_saddr);
339 }
340 
TEST(elftls_dl,dl_iterate_phdr)341 TEST(elftls_dl, dl_iterate_phdr) {
342   void* lib = dlopen("libtest_elftls_dynamic.so", RTLD_LOCAL | RTLD_NOW);
343 
344   auto get_var_addr = reinterpret_cast<void*(*)()>(dlsym(lib, "get_large_tls_var_addr"));
345   ASSERT_NE(nullptr, get_var_addr);
346 
347   struct TlsInfo {
348     bool found;
349     size_t modid;
350     void* data;
351     size_t memsz;
352   };
353 
354   auto get_tls_info = []() {
355     auto callback = [](dl_phdr_info* info, size_t, void* data) {
356       TlsInfo& tls_info = *static_cast<TlsInfo*>(data);
357 
358       // This test is also run with glibc, where dlpi_name may have relative path components, so
359       // examine just the basename when searching for the library.
360       if (strcmp(android::base::Basename(info->dlpi_name).c_str(), "libtest_elftls_dynamic.so") != 0) return 0;
361 
362       tls_info.found = true;
363       tls_info.modid = info->dlpi_tls_modid;
364       tls_info.data = info->dlpi_tls_data;
365       for (ElfW(Half) i = 0; i < info->dlpi_phnum; ++i) {
366         if (info->dlpi_phdr[i].p_type == PT_TLS) {
367           tls_info.memsz = info->dlpi_phdr[i].p_memsz;
368         }
369       }
370       EXPECT_NE(static_cast<size_t>(0), tls_info.memsz);
371       return 1;
372     };
373 
374     TlsInfo result {};
375     dl_iterate_phdr(callback, &result);
376     return result;
377   };
378 
379   // The executable has a TLS segment, so it will use module ID #1, and the DSO's ID will be larger
380   // than 1. Initially, the data field is nullptr, because this thread's instance hasn't been
381   // allocated yet.
382   TlsInfo tls_info = get_tls_info();
383   ASSERT_TRUE(tls_info.found);
384   ASSERT_GT(tls_info.modid, static_cast<size_t>(1));
385   ASSERT_EQ(nullptr, tls_info.data);
386 
387   void* var_addr = get_var_addr();
388 
389   // Verify that dl_iterate_phdr returns a range of memory covering the allocated TLS variable.
390   tls_info = get_tls_info();
391   ASSERT_TRUE(tls_info.found);
392   ASSERT_GE(var_addr, tls_info.data);
393   ASSERT_LT(var_addr, static_cast<char*>(tls_info.data) + tls_info.memsz);
394 }
395