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