• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <gtest/gtest.h>
18 
19 #include <dlfcn.h>
20 #include <limits.h>
21 #include <stdio.h>
22 #include <stdint.h>
23 #include <string.h>
24 #if __has_include(<sys/auxv.h>)
25 #include <sys/auxv.h>
26 #endif
27 #include <sys/user.h>
28 
29 #include <string>
30 #include <thread>
31 
32 #include <android-base/file.h>
33 #include <android-base/scopeguard.h>
34 
35 #include "gtest_globals.h"
36 #include "gtest_utils.h"
37 #include "dlfcn_symlink_support.h"
38 #include "utils.h"
39 
40 #if defined(__BIONIC__) && (defined(__arm__) || defined(__i386__))
41 #pragma clang diagnostic push
42 #pragma clang diagnostic ignored "-Wunused-parameter"
43 
44 #include <llvm/ADT/StringRef.h>
45 #include <llvm/Object/Binary.h>
46 #include <llvm/Object/ELFObjectFile.h>
47 #include <llvm/Object/ObjectFile.h>
48 
49 #pragma clang diagnostic pop
50 #endif //  defined(__ANDROID__) && (defined(__arm__) || defined(__i386__))
51 
52 // Declared manually because the macro definitions in <elf.h> conflict with LLVM headers.
53 #ifdef __arm__
54 typedef uintptr_t _Unwind_Ptr;
55 extern "C" _Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr, int*);
56 #endif
57 
58 #define ASSERT_SUBSTR(needle, haystack) \
59     ASSERT_PRED_FORMAT2(::testing::IsSubstring, needle, haystack)
60 
61 
62 static bool g_called = false;
DlSymTestFunction()63 extern "C" void DlSymTestFunction() {
64   g_called = true;
65 }
66 
67 static int g_ctor_function_called = 0;
68 static int g_ctor_argc = 0;
69 static char** g_ctor_argv = reinterpret_cast<char**>(0xDEADBEEF);
70 static char** g_ctor_envp = g_ctor_envp;
71 
72 extern "C" void ctor_function(int argc, char** argv, char** envp) __attribute__ ((constructor));
73 
ctor_function(int argc,char ** argv,char ** envp)74 extern "C" void ctor_function(int argc, char** argv, char** envp) {
75   g_ctor_function_called = 17;
76   g_ctor_argc = argc;
77   g_ctor_argv = argv;
78   g_ctor_envp = envp;
79 }
80 
TEST(dlfcn,ctor_function_call)81 TEST(dlfcn, ctor_function_call) {
82   ASSERT_EQ(17, g_ctor_function_called);
83   ASSERT_TRUE(g_ctor_argc = GetArgc());
84   ASSERT_TRUE(g_ctor_argv = GetArgv());
85   ASSERT_TRUE(g_ctor_envp = GetEnvp());
86 }
87 
TEST(dlfcn,dlsym_in_executable)88 TEST(dlfcn, dlsym_in_executable) {
89   dlerror(); // Clear any pending errors.
90   void* self = dlopen(nullptr, RTLD_NOW);
91   ASSERT_TRUE(self != nullptr);
92   ASSERT_TRUE(dlerror() == nullptr);
93 
94   void* sym = dlsym(self, "DlSymTestFunction");
95   ASSERT_TRUE(sym != nullptr);
96 
97   void (*function)() = reinterpret_cast<void(*)()>(sym);
98 
99   g_called = false;
100   function();
101   ASSERT_TRUE(g_called);
102 
103   ASSERT_EQ(0, dlclose(self));
104 }
105 
TEST(dlfcn,dlsym_from_sofile)106 TEST(dlfcn, dlsym_from_sofile) {
107   void* handle = dlopen("libtest_dlsym_from_this.so", RTLD_LAZY | RTLD_LOCAL);
108   ASSERT_TRUE(handle != nullptr) << dlerror();
109 
110   // check that we can't find '_test_dlsym_symbol' via dlsym(RTLD_DEFAULT)
111   void* symbol = dlsym(RTLD_DEFAULT, "test_dlsym_symbol");
112   ASSERT_TRUE(symbol == nullptr);
113   ASSERT_SUBSTR("undefined symbol: test_dlsym_symbol", dlerror());
114 
115   typedef int* (*fn_t)();
116   fn_t lookup_dlsym_symbol_using_RTLD_DEFAULT =
117       reinterpret_cast<fn_t>(dlsym(handle, "lookup_dlsym_symbol_using_RTLD_DEFAULT"));
118   ASSERT_TRUE(lookup_dlsym_symbol_using_RTLD_DEFAULT != nullptr) << dlerror();
119 
120   int* ptr = lookup_dlsym_symbol_using_RTLD_DEFAULT();
121   ASSERT_TRUE(ptr != nullptr) << dlerror();
122   ASSERT_EQ(42, *ptr);
123 
124   fn_t lookup_dlsym_symbol2_using_RTLD_DEFAULT =
125       reinterpret_cast<fn_t>(dlsym(handle, "lookup_dlsym_symbol2_using_RTLD_DEFAULT"));
126   ASSERT_TRUE(lookup_dlsym_symbol2_using_RTLD_DEFAULT != nullptr) << dlerror();
127 
128   ptr = lookup_dlsym_symbol2_using_RTLD_DEFAULT();
129   ASSERT_TRUE(ptr != nullptr) << dlerror();
130   ASSERT_EQ(44, *ptr);
131 
132   fn_t lookup_dlsym_symbol_using_RTLD_NEXT =
133       reinterpret_cast<fn_t>(dlsym(handle, "lookup_dlsym_symbol_using_RTLD_NEXT"));
134   ASSERT_TRUE(lookup_dlsym_symbol_using_RTLD_NEXT != nullptr) << dlerror();
135 
136   ptr = lookup_dlsym_symbol_using_RTLD_NEXT();
137   ASSERT_TRUE(ptr != nullptr) << dlerror();
138   ASSERT_EQ(43, *ptr);
139 
140   dlclose(handle);
141 }
142 
TEST(dlfcn,dlsym_from_sofile_with_preload)143 TEST(dlfcn, dlsym_from_sofile_with_preload) {
144   void* preload = dlopen("libtest_dlsym_from_this_grandchild.so", RTLD_NOW | RTLD_LOCAL);
145   ASSERT_TRUE(preload != nullptr) << dlerror();
146 
147   void* handle = dlopen("libtest_dlsym_from_this.so", RTLD_NOW | RTLD_LOCAL);
148   ASSERT_TRUE(handle != nullptr) << dlerror();
149 
150   // check that we can't find '_test_dlsym_symbol' via dlsym(RTLD_DEFAULT)
151   void* symbol = dlsym(RTLD_DEFAULT, "test_dlsym_symbol");
152   ASSERT_TRUE(symbol == nullptr);
153   ASSERT_SUBSTR("undefined symbol: test_dlsym_symbol", dlerror());
154 
155   typedef int* (*fn_t)();
156   fn_t lookup_dlsym_symbol_using_RTLD_DEFAULT =
157       reinterpret_cast<fn_t>(dlsym(handle, "lookup_dlsym_symbol_using_RTLD_DEFAULT"));
158   ASSERT_TRUE(lookup_dlsym_symbol_using_RTLD_DEFAULT != nullptr) << dlerror();
159 
160   int* ptr = lookup_dlsym_symbol_using_RTLD_DEFAULT();
161   ASSERT_TRUE(ptr != nullptr) << dlerror();
162   ASSERT_EQ(42, *ptr);
163 
164   fn_t lookup_dlsym_symbol2_using_RTLD_DEFAULT =
165       reinterpret_cast<fn_t>(dlsym(handle, "lookup_dlsym_symbol2_using_RTLD_DEFAULT"));
166   ASSERT_TRUE(lookup_dlsym_symbol2_using_RTLD_DEFAULT != nullptr) << dlerror();
167 
168   ptr = lookup_dlsym_symbol2_using_RTLD_DEFAULT();
169   ASSERT_TRUE(ptr != nullptr) << dlerror();
170   ASSERT_EQ(44, *ptr);
171 
172   fn_t lookup_dlsym_symbol_using_RTLD_NEXT =
173       reinterpret_cast<fn_t>(dlsym(handle, "lookup_dlsym_symbol_using_RTLD_NEXT"));
174   ASSERT_TRUE(lookup_dlsym_symbol_using_RTLD_NEXT != nullptr) << dlerror();
175 
176   ptr = lookup_dlsym_symbol_using_RTLD_NEXT();
177   ASSERT_TRUE(ptr != nullptr) << dlerror();
178   ASSERT_EQ(43, *ptr);
179 
180   dlclose(handle);
181   dlclose(preload);
182 }
183 
TEST(dlfcn,dlsym_handle_global_sym)184 TEST(dlfcn, dlsym_handle_global_sym) {
185   // check that we do not look into global group
186   // when looking up symbol by handle
187   void* handle = dlopen("libtest_empty.so", RTLD_NOW);
188   dlopen("libtest_with_dependency.so", RTLD_NOW | RTLD_GLOBAL);
189   void* sym = dlsym(handle, "getRandomNumber");
190   ASSERT_TRUE(sym == nullptr);
191   ASSERT_SUBSTR("undefined symbol: getRandomNumber", dlerror());
192 
193   sym = dlsym(handle, "DlSymTestFunction");
194   ASSERT_TRUE(sym == nullptr);
195   ASSERT_SUBSTR("undefined symbol: DlSymTestFunction", dlerror());
196   dlclose(handle);
197 }
198 
TEST(dlfcn,dlsym_handle_empty_symbol)199 TEST(dlfcn, dlsym_handle_empty_symbol) {
200   // check that dlsym of an empty symbol fails (see http://b/33530622)
201   void* handle = dlopen("libtest_dlsym_from_this.so", RTLD_NOW);
202   ASSERT_TRUE(handle != nullptr) << dlerror();
203   void* sym = dlsym(handle, "");
204   ASSERT_TRUE(sym == nullptr);
205   ASSERT_SUBSTR("undefined symbol: ", dlerror());
206   dlclose(handle);
207 }
208 
TEST(dlfcn,dlsym_with_dependencies)209 TEST(dlfcn, dlsym_with_dependencies) {
210   void* handle = dlopen("libtest_with_dependency.so", RTLD_NOW);
211   ASSERT_TRUE(handle != nullptr);
212   dlerror();
213   // This symbol is in DT_NEEDED library.
214   void* sym = dlsym(handle, "getRandomNumber");
215   ASSERT_TRUE(sym != nullptr) << dlerror();
216   int (*fn)(void);
217   fn = reinterpret_cast<int (*)(void)>(sym);
218   EXPECT_EQ(4, fn());
219   dlclose(handle);
220 }
221 
TEST(dlfcn,dlopen_noload)222 TEST(dlfcn, dlopen_noload) {
223   void* handle = dlopen("libtest_simple.so", RTLD_NOW | RTLD_NOLOAD);
224   ASSERT_TRUE(handle == nullptr);
225   handle = dlopen("libtest_simple.so", RTLD_NOW);
226   void* handle2 = dlopen("libtest_simple.so", RTLD_NOW | RTLD_NOLOAD);
227   ASSERT_TRUE(handle != nullptr);
228   ASSERT_TRUE(handle2 != nullptr);
229   ASSERT_TRUE(handle == handle2);
230   ASSERT_EQ(0, dlclose(handle));
231   ASSERT_EQ(0, dlclose(handle2));
232 }
233 
TEST(dlfcn,dlopen_by_soname)234 TEST(dlfcn, dlopen_by_soname) {
235   static const char* soname = "libdlext_test_soname.so";
236   static const char* filename = "libdlext_test_different_soname.so";
237   // 1. Make sure there is no library with soname in default search path
238   void* handle = dlopen(soname, RTLD_NOW);
239   ASSERT_TRUE(handle == nullptr);
240 
241   // 2. Load a library using filename
242   handle = dlopen(filename, RTLD_NOW);
243   ASSERT_TRUE(handle != nullptr) << dlerror();
244 
245   // 3. Find library by soname
246   void* handle_soname = dlopen(soname, RTLD_NOW | RTLD_NOLOAD);
247   ASSERT_TRUE(handle_soname != nullptr) << dlerror();
248   ASSERT_EQ(handle, handle_soname);
249 
250   // 4. RTLD_NOLOAD should still work with filename
251   void* handle_filename = dlopen(filename, RTLD_NOW | RTLD_NOLOAD);
252   ASSERT_TRUE(handle_filename != nullptr) << dlerror();
253   ASSERT_EQ(handle, handle_filename);
254 
255   dlclose(handle_filename);
256   dlclose(handle_soname);
257   dlclose(handle);
258 }
259 
TEST(dlfcn,dlopen_vdso)260 TEST(dlfcn, dlopen_vdso) {
261 #if __has_include(<sys/auxv.h>)
262   if (getauxval(AT_SYSINFO_EHDR) == 0) {
263     GTEST_SKIP() << "getauxval(AT_SYSINFO_EHDR) == 0, skipping this test";
264   }
265 #endif
266 
267   const char* vdso_name = "linux-vdso.so.1";
268 #if defined(__i386__)
269   vdso_name = "linux-gate.so.1";
270 #endif
271   void* handle = dlopen(vdso_name, RTLD_NOW);
272   ASSERT_TRUE(handle != nullptr) << dlerror();
273   dlclose(handle);
274 }
275 
276 // mips doesn't support ifuncs
277 #if !defined(__mips__)
TEST(dlfcn,ifunc_variable)278 TEST(dlfcn, ifunc_variable) {
279   typedef const char* (*fn_ptr)();
280 
281   // ifunc's choice depends on whether IFUNC_CHOICE has a value
282   // first check the set case
283   setenv("IFUNC_CHOICE", "set", 1);
284   // preload libtest_ifunc_variable_impl.so
285   void* handle_impl = dlopen("libtest_ifunc_variable_impl.so", RTLD_NOW);
286   void* handle = dlopen("libtest_ifunc_variable.so", RTLD_NOW);
287   ASSERT_TRUE(handle != nullptr) << dlerror();
288   const char** foo_ptr = reinterpret_cast<const char**>(dlsym(handle, "foo"));
289   fn_ptr foo_library_ptr = reinterpret_cast<fn_ptr>(dlsym(handle, "foo_library"));
290   ASSERT_TRUE(foo_ptr != nullptr) << dlerror();
291   ASSERT_TRUE(foo_library_ptr != nullptr) << dlerror();
292   ASSERT_EQ(strncmp("set", *foo_ptr, 3), 0);
293   ASSERT_EQ(strncmp("set", foo_library_ptr(), 3), 0);
294   dlclose(handle);
295   dlclose(handle_impl);
296 
297   // then check the unset case
298   unsetenv("IFUNC_CHOICE");
299   handle_impl = dlopen("libtest_ifunc_variable_impl.so", RTLD_NOW);
300   handle = dlopen("libtest_ifunc_variable.so", RTLD_NOW);
301   ASSERT_TRUE(handle != nullptr) << dlerror();
302   foo_ptr = reinterpret_cast<const char**>(dlsym(handle, "foo"));
303   foo_library_ptr = reinterpret_cast<fn_ptr>(dlsym(handle, "foo_library"));
304   ASSERT_TRUE(foo_ptr != nullptr) << dlerror();
305   ASSERT_TRUE(foo_library_ptr != nullptr) << dlerror();
306   ASSERT_EQ(strncmp("unset", *foo_ptr, 5), 0);
307   ASSERT_EQ(strncmp("unset", foo_library_ptr(), 5), 0);
308   dlclose(handle);
309   dlclose(handle_impl);
310 }
311 
TEST(dlfcn,ifunc)312 TEST(dlfcn, ifunc) {
313   typedef const char* (*fn_ptr)();
314 
315   // ifunc's choice depends on whether IFUNC_CHOICE has a value
316   // first check the set case
317   setenv("IFUNC_CHOICE", "set", 1);
318   void* handle = dlopen("libtest_ifunc.so", RTLD_NOW);
319   ASSERT_TRUE(handle != nullptr) << dlerror();
320   fn_ptr foo_ptr = reinterpret_cast<fn_ptr>(dlsym(handle, "foo"));
321   fn_ptr foo_library_ptr = reinterpret_cast<fn_ptr>(dlsym(handle, "foo_library"));
322   ASSERT_TRUE(foo_ptr != nullptr) << dlerror();
323   ASSERT_TRUE(foo_library_ptr != nullptr) << dlerror();
324   ASSERT_EQ(strncmp("set", foo_ptr(), 3), 0);
325   ASSERT_EQ(strncmp("set", foo_library_ptr(), 3), 0);
326   dlclose(handle);
327 
328   // then check the unset case
329   unsetenv("IFUNC_CHOICE");
330   handle = dlopen("libtest_ifunc.so", RTLD_NOW);
331   ASSERT_TRUE(handle != nullptr) << dlerror();
332   foo_ptr = reinterpret_cast<fn_ptr>(dlsym(handle, "foo"));
333   foo_library_ptr = reinterpret_cast<fn_ptr>(dlsym(handle, "foo_library"));
334   ASSERT_TRUE(foo_ptr != nullptr) << dlerror();
335   ASSERT_TRUE(foo_library_ptr != nullptr) << dlerror();
336   ASSERT_EQ(strncmp("unset", foo_ptr(), 5), 0);
337   ASSERT_EQ(strncmp("unset", foo_library_ptr(), 5), 0);
338   dlclose(handle);
339 }
340 
TEST(dlfcn,ifunc_ctor_call)341 TEST(dlfcn, ifunc_ctor_call) {
342   typedef const char* (*fn_ptr)();
343 
344   void* handle = dlopen("libtest_ifunc.so", RTLD_NOW);
345   ASSERT_TRUE(handle != nullptr) << dlerror();
346   fn_ptr is_ctor_called =  reinterpret_cast<fn_ptr>(dlsym(handle, "is_ctor_called_irelative"));
347   ASSERT_TRUE(is_ctor_called != nullptr) << dlerror();
348   ASSERT_STREQ("false", is_ctor_called());
349 
350   is_ctor_called =  reinterpret_cast<fn_ptr>(dlsym(handle, "is_ctor_called_jump_slot"));
351   ASSERT_TRUE(is_ctor_called != nullptr) << dlerror();
352   ASSERT_STREQ("true", is_ctor_called());
353   dlclose(handle);
354 }
355 
TEST(dlfcn,ifunc_ctor_call_rtld_lazy)356 TEST(dlfcn, ifunc_ctor_call_rtld_lazy) {
357   typedef const char* (*fn_ptr)();
358 
359   void* handle = dlopen("libtest_ifunc.so", RTLD_LAZY);
360   ASSERT_TRUE(handle != nullptr) << dlerror();
361   fn_ptr is_ctor_called =  reinterpret_cast<fn_ptr>(dlsym(handle, "is_ctor_called_irelative"));
362   ASSERT_TRUE(is_ctor_called != nullptr) << dlerror();
363   ASSERT_STREQ("false", is_ctor_called());
364 
365   is_ctor_called =  reinterpret_cast<fn_ptr>(dlsym(handle, "is_ctor_called_jump_slot"));
366   ASSERT_TRUE(is_ctor_called != nullptr) << dlerror();
367   ASSERT_STREQ("true", is_ctor_called());
368   dlclose(handle);
369 }
370 #endif
371 
TEST(dlfcn,dlopen_check_relocation_dt_needed_order)372 TEST(dlfcn, dlopen_check_relocation_dt_needed_order) {
373   // This is the structure of the test library and
374   // its dt_needed libraries
375   // libtest_relo_check_dt_needed_order.so
376   // |
377   // +-> libtest_relo_check_dt_needed_order_1.so
378   // |
379   // +-> libtest_relo_check_dt_needed_order_2.so
380   //
381   // The root library references relo_test_get_answer_lib - which is defined
382   // in both dt_needed libraries, the correct relocation should
383   // use the function defined in libtest_relo_check_dt_needed_order_1.so
384   void* handle = nullptr;
385   auto guard = android::base::make_scope_guard([&]() { dlclose(handle); });
386 
387   handle = dlopen("libtest_relo_check_dt_needed_order.so", RTLD_NOW);
388   ASSERT_TRUE(handle != nullptr) << dlerror();
389 
390   typedef int (*fn_t) (void);
391   fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "relo_test_get_answer"));
392   ASSERT_TRUE(fn != nullptr) << dlerror();
393   ASSERT_EQ(1, fn());
394 }
395 
TEST(dlfcn,dlopen_check_order_dlsym)396 TEST(dlfcn, dlopen_check_order_dlsym) {
397   // Here is how the test library and its dt_needed
398   // libraries are arranged
399   //
400   //  libtest_check_order_children.so
401   //  |
402   //  +-> ..._1_left.so
403   //  |   |
404   //  |   +-> ..._a.so
405   //  |   |
406   //  |   +-> ...r_b.so
407   //  |
408   //  +-> ..._2_right.so
409   //  |   |
410   //  |   +-> ..._d.so
411   //  |       |
412   //  |       +-> ..._b.so
413   //  |
414   //  +-> ..._3_c.so
415   //
416   //  load order should be (1, 2, 3, a, b, d)
417   //
418   // get_answer() is defined in (2, 3, a, b, c)
419   // get_answer2() is defined in (b, d)
420   void* sym = dlsym(RTLD_DEFAULT, "check_order_dlsym_get_answer");
421   ASSERT_TRUE(sym == nullptr);
422   void* handle = dlopen("libtest_check_order_dlsym.so", RTLD_NOW | RTLD_GLOBAL);
423   ASSERT_TRUE(handle != nullptr) << dlerror();
424   typedef int (*fn_t) (void);
425   fn_t fn, fn2;
426   fn = reinterpret_cast<fn_t>(dlsym(RTLD_DEFAULT, "check_order_dlsym_get_answer"));
427   ASSERT_TRUE(fn != nullptr) << dlerror();
428   fn2 = reinterpret_cast<fn_t>(dlsym(RTLD_DEFAULT, "check_order_dlsym_get_answer2"));
429   ASSERT_TRUE(fn2 != nullptr) << dlerror();
430 
431   ASSERT_EQ(42, fn());
432   ASSERT_EQ(43, fn2());
433   dlclose(handle);
434 }
435 
TEST(dlfcn,dlopen_check_order_reloc_siblings)436 TEST(dlfcn, dlopen_check_order_reloc_siblings) {
437   // This is how this one works:
438   // we lookup and call get_answer which is defined in '_2.so'
439   // and in turn calls external get_answer_impl() defined in _1.so and in '_[a-f].so'
440   // the correct _impl() is implemented by '_a.so';
441   //
442   // Note that this is test for RTLD_LOCAL (TODO: test for GLOBAL?)
443   //
444   // Here is the picture:
445   //
446   // libtest_check_order_reloc_siblings.so
447   // |
448   // +-> ..._1.so <- empty
449   // |   |
450   // |   +-> ..._a.so <- exports correct answer_impl()
451   // |   |
452   // |   +-> ..._b.so <- every other letter exporting incorrect one.
453   // |
454   // +-> ..._2.so <- empty
455   // |   |
456   // |   +-> ..._c.so
457   // |   |
458   // |   +-> ..._d.so
459   // |
460   // +-> ..._3.so <- empty
461   //     |
462   //     +-> ..._e.so
463   //     |
464   //     +-> ..._f.so <- exports get_answer() that calls get_anser_impl();
465   //                     implements incorrect get_answer_impl()
466 
467   void* handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_NOLOAD);
468   ASSERT_TRUE(handle == nullptr);
469 #ifdef __BIONIC__
470   // TODO: glibc returns nullptr on dlerror() here. Is it bug?
471   ASSERT_STREQ("dlopen failed: library \"libtest_check_order_reloc_siblings.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
472 #endif
473 
474   handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_LOCAL);
475   ASSERT_TRUE(handle != nullptr) << dlerror();
476 
477   typedef int (*fn_t) (void);
478   fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "check_order_reloc_get_answer"));
479   ASSERT_TRUE(fn != nullptr) << dlerror();
480   ASSERT_EQ(42, fn());
481 
482   ASSERT_EQ(0, dlclose(handle));
483 }
484 
TEST(dlfcn,dlopen_check_order_reloc_siblings_with_preload)485 TEST(dlfcn, dlopen_check_order_reloc_siblings_with_preload) {
486   // This test uses the same library as dlopen_check_order_reloc_siblings.
487   // Unlike dlopen_check_order_reloc_siblings it preloads
488   // libtest_check_order_reloc_siblings_1.so (first dependency) prior to
489   // dlopen(libtest_check_order_reloc_siblings.so)
490 
491   void* handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_NOLOAD);
492   ASSERT_TRUE(handle == nullptr);
493   handle = dlopen("libtest_check_order_reloc_siblings_1.so", RTLD_NOW | RTLD_NOLOAD);
494   ASSERT_TRUE(handle == nullptr);
495 
496   void* handle_for_1 = dlopen("libtest_check_order_reloc_siblings_1.so", RTLD_NOW | RTLD_LOCAL);
497   ASSERT_TRUE(handle_for_1 != nullptr) << dlerror();
498 
499   handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_LOCAL);
500   ASSERT_TRUE(handle != nullptr) << dlerror();
501 
502   ASSERT_EQ(0, dlclose(handle_for_1));
503 
504   typedef int (*fn_t) (void);
505   fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "check_order_reloc_get_answer"));
506   ASSERT_TRUE(fn != nullptr) << dlerror();
507   ASSERT_EQ(42, fn());
508 
509   ASSERT_EQ(0, dlclose(handle));
510 }
511 
TEST(dlfcn,dlopen_check_order_reloc_grandchild)512 TEST(dlfcn, dlopen_check_order_reloc_grandchild) {
513   // This is how this one works:
514   // we lookup and call grandchild_get_answer which is defined in '_2.so'
515   // and in turn calls external get_answer_impl() defined in '_c_1.so and _c_2.so'
516   // the correct _impl() is implemented by '_c_1.so';
517   //
518   // Here is the picture of subtree:
519   //
520   // libtest_check_order_reloc_siblings.so
521   // |
522   // +-> ..._2.so <- grandchild_get_answer()
523   //     |
524   //     +-> ..._c.so <- empty
525   //     |   |
526   //     |   +-> _c_1.so <- exports correct answer_impl()
527   //     |   |
528   //     |   +-> _c_2.so <- exports incorrect answer_impl()
529   //     |
530   //     +-> ..._d.so <- empty
531 
532   void* handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_NOLOAD);
533   ASSERT_TRUE(handle == nullptr);
534 #ifdef __BIONIC__
535   // TODO: glibc returns nullptr on dlerror() here. Is it bug?
536   ASSERT_STREQ("dlopen failed: library \"libtest_check_order_reloc_siblings.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
537 #endif
538 
539   handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_LOCAL);
540   ASSERT_TRUE(handle != nullptr) << dlerror();
541 
542   typedef int (*fn_t) (void);
543   fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "check_order_reloc_grandchild_get_answer"));
544   ASSERT_TRUE(fn != nullptr) << dlerror();
545   ASSERT_EQ(42, fn());
546 
547   ASSERT_EQ(0, dlclose(handle));
548 }
549 
TEST(dlfcn,dlopen_check_order_reloc_nephew)550 TEST(dlfcn, dlopen_check_order_reloc_nephew) {
551   // This is how this one works:
552   // we lookup and call nephew_get_answer which is defined in '_2.so'
553   // and in turn calls external get_answer_impl() defined in '_[a-f].so'
554   // the correct _impl() is implemented by '_a.so';
555   //
556   // Here is the picture:
557   //
558   // libtest_check_order_reloc_siblings.so
559   // |
560   // +-> ..._1.so <- empty
561   // |   |
562   // |   +-> ..._a.so <- exports correct answer_impl()
563   // |   |
564   // |   +-> ..._b.so <- every other letter exporting incorrect one.
565   // |
566   // +-> ..._2.so <- empty
567   // |   |
568   // |   +-> ..._c.so
569   // |   |
570   // |   +-> ..._d.so
571   // |
572   // +-> ..._3.so <- nephew_get_answer() that calls get_answer_impl();
573   //     |
574   //     +-> ..._e.so
575   //     |
576   //     +-> ..._f.so
577 
578   void* handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_NOLOAD);
579   ASSERT_TRUE(handle == nullptr);
580 #ifdef __BIONIC__
581   // TODO: glibc returns nullptr on dlerror() here. Is it bug?
582   ASSERT_STREQ("dlopen failed: library \"libtest_check_order_reloc_siblings.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
583 #endif
584 
585   handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_LOCAL);
586   ASSERT_TRUE(handle != nullptr) << dlerror();
587 
588   typedef int (*fn_t) (void);
589   fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "check_order_reloc_nephew_get_answer"));
590   ASSERT_TRUE(fn != nullptr) << dlerror();
591   ASSERT_EQ(42, fn());
592 
593   ASSERT_EQ(0, dlclose(handle));
594 }
595 
TEST(dlfcn,check_unload_after_reloc)596 TEST(dlfcn, check_unload_after_reloc) {
597   // This is how this one works:
598   // libtest_two_parents_parent1 <- answer_impl() used by libtest_two_parents_child
599   // |
600   // +-> libtest_two_parents_child
601   //
602   // libtest_two_parents_parent2 <- answer_impl() not used by libtest_two_parents_child
603   // |
604   // +-> libtest_two_parents_child
605   //
606   // Test dlopens parent1 which loads and relocates libtest_two_parents_child.so
607   // as a second step it dlopens parent2 and dlcloses parent1...
608 
609   void* handle = dlopen("libtest_two_parents_parent1.so", RTLD_NOW | RTLD_LOCAL);
610   ASSERT_TRUE(handle != nullptr) << dlerror();
611 
612   void* handle2 = dlopen("libtest_two_parents_parent2.so", RTLD_NOW | RTLD_LOCAL);
613   ASSERT_TRUE(handle2 != nullptr) << dlerror();
614 
615   typedef int (*fn_t) (void);
616   fn_t fn = reinterpret_cast<fn_t>(dlsym(handle2, "check_order_reloc_get_answer"));
617   ASSERT_TRUE(fn != nullptr) << dlerror();
618   ASSERT_EQ(42, fn());
619 
620   ASSERT_EQ(0, dlclose(handle));
621 
622   handle = dlopen("libtest_two_parents_parent1.so", RTLD_NOW | RTLD_LOCAL | RTLD_NOLOAD);
623   ASSERT_TRUE(handle != nullptr);
624   ASSERT_EQ(0, dlclose(handle));
625 
626   fn = reinterpret_cast<fn_t>(dlsym(handle2, "check_order_reloc_get_answer"));
627   ASSERT_TRUE(fn != nullptr) << dlerror();
628   ASSERT_EQ(42, fn());
629 
630   ASSERT_EQ(0, dlclose(handle2));
631 
632   handle = dlopen("libtest_two_parents_parent1.so", RTLD_NOW | RTLD_LOCAL | RTLD_NOLOAD);
633   ASSERT_TRUE(handle == nullptr);
634 }
635 
check_order_reloc_root_get_answer_impl()636 extern "C" int check_order_reloc_root_get_answer_impl() {
637   return 42;
638 }
639 
TEST(dlfcn,dlopen_check_order_reloc_main_executable)640 TEST(dlfcn, dlopen_check_order_reloc_main_executable) {
641   // This is how this one works:
642   // we lookup and call get_answer3 which is defined in 'root.so'
643   // and in turn calls external root_get_answer_impl() defined in _2.so and
644   // above the correct _impl() is one in the executable.
645   //
646   // libtest_check_order_reloc_root.so
647   // |
648   // +-> ..._1.so <- empty
649   // |
650   // +-> ..._2.so <- gives incorrect answer for answer_main_impl()
651   //
652 
653   void* handle = dlopen("libtest_check_order_reloc_root.so", RTLD_NOW | RTLD_NOLOAD);
654   ASSERT_TRUE(handle == nullptr);
655 #ifdef __BIONIC__
656   // TODO: glibc returns nullptr on dlerror() here. Is it bug?
657   ASSERT_STREQ("dlopen failed: library \"libtest_check_order_reloc_root.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
658 #endif
659 
660   handle = dlopen("libtest_check_order_reloc_root.so", RTLD_NOW | RTLD_LOCAL);
661   ASSERT_TRUE(handle != nullptr) << dlerror();
662 
663   typedef int (*fn_t) (void);
664   fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "check_order_reloc_root_get_answer"));
665   ASSERT_TRUE(fn != nullptr) << dlerror();
666   ASSERT_EQ(42, fn());
667 
668   ASSERT_EQ(0, dlclose(handle));
669 }
670 
TEST(dlfcn,dlopen_check_rtld_local)671 TEST(dlfcn, dlopen_check_rtld_local) {
672   void* sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func");
673   ASSERT_TRUE(sym == nullptr);
674 
675   // implicit RTLD_LOCAL
676   void* handle = dlopen("libtest_simple.so", RTLD_NOW);
677   sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func");
678   ASSERT_TRUE(sym == nullptr);
679   ASSERT_SUBSTR("undefined symbol: dlopen_testlib_simple_func", dlerror());
680   sym = dlsym(handle, "dlopen_testlib_simple_func");
681   ASSERT_TRUE(sym != nullptr);
682   ASSERT_TRUE(reinterpret_cast<bool (*)(void)>(sym)());
683   dlclose(handle);
684 
685   // explicit RTLD_LOCAL
686   handle = dlopen("libtest_simple.so", RTLD_NOW | RTLD_LOCAL);
687   sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func");
688   ASSERT_TRUE(sym == nullptr);
689   ASSERT_SUBSTR("undefined symbol: dlopen_testlib_simple_func", dlerror());
690   sym = dlsym(handle, "dlopen_testlib_simple_func");
691   ASSERT_TRUE(sym != nullptr);
692   ASSERT_TRUE(reinterpret_cast<bool (*)(void)>(sym)());
693   dlclose(handle);
694 }
695 
TEST(dlfcn,dlopen_check_rtld_global)696 TEST(dlfcn, dlopen_check_rtld_global) {
697   void* sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func");
698   ASSERT_TRUE(sym == nullptr);
699 
700   void* handle = dlopen("libtest_simple.so", RTLD_NOW | RTLD_GLOBAL);
701   ASSERT_TRUE(handle != nullptr) << dlerror();
702   sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func");
703   ASSERT_TRUE(sym != nullptr) << dlerror();
704   ASSERT_TRUE(reinterpret_cast<bool (*)(void)>(sym)());
705   dlclose(handle);
706 
707   // RTLD_GLOBAL implies RTLD_NODELETE, let's check that
708   void* sym_after_dlclose = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func");
709   ASSERT_EQ(sym, sym_after_dlclose);
710 
711   // Check if dlsym() for main program's handle searches RTLD_GLOBAL
712   // shared libraries after symbol was not found in the main executable
713   // and dependent libraries.
714   void* handle_for_main_executable = dlopen(nullptr, RTLD_NOW);
715   sym = dlsym(handle_for_main_executable, "dlopen_testlib_simple_func");
716   ASSERT_TRUE(sym != nullptr) << dlerror();
717 
718   dlclose(handle_for_main_executable);
719 }
720 
721 // libtest_with_dependency_loop.so -> libtest_with_dependency_loop_a.so ->
722 // libtest_with_dependency_loop_b.so -> libtest_with_dependency_loop_c.so ->
723 // libtest_with_dependency_loop_a.so
TEST(dlfcn,dlopen_check_loop)724 TEST(dlfcn, dlopen_check_loop) {
725   void* handle = dlopen("libtest_with_dependency_loop.so", RTLD_NOW);
726   ASSERT_TRUE(handle != nullptr) << dlerror();
727   void* f = dlsym(handle, "dlopen_test_loopy_function");
728   ASSERT_TRUE(f != nullptr) << dlerror();
729   EXPECT_TRUE(reinterpret_cast<bool (*)(void)>(f)());
730   ASSERT_EQ(0, dlclose(handle));
731 
732   // dlopen second time to make sure that the library was unloaded correctly
733   handle = dlopen("libtest_with_dependency_loop.so", RTLD_NOW | RTLD_NOLOAD);
734   ASSERT_TRUE(handle == nullptr);
735 #ifdef __BIONIC__
736   ASSERT_STREQ("dlopen failed: library \"libtest_with_dependency_loop.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
737 #else
738   // TODO: glibc returns nullptr on dlerror() here. Is it bug?
739   ASSERT_TRUE(dlerror() == nullptr);
740 #endif
741 
742   handle = dlopen("libtest_with_dependency_a.so", RTLD_NOW | RTLD_NOLOAD);
743   ASSERT_TRUE(handle == nullptr);
744 }
745 
TEST(dlfcn,dlopen_nodelete)746 TEST(dlfcn, dlopen_nodelete) {
747   static bool is_unloaded = false;
748 
749   void* handle = dlopen("libtest_nodelete_1.so", RTLD_NOW | RTLD_NODELETE);
750   ASSERT_TRUE(handle != nullptr) << dlerror();
751   void (*set_unload_flag_ptr)(bool*);
752   set_unload_flag_ptr = reinterpret_cast<void (*)(bool*)>(dlsym(handle, "dlopen_nodelete_1_set_unload_flag_ptr"));
753   ASSERT_TRUE(set_unload_flag_ptr != nullptr) << dlerror();
754   set_unload_flag_ptr(&is_unloaded);
755 
756   uint32_t* taxicab_number = reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_nodelete_1_taxicab_number"));
757   ASSERT_TRUE(taxicab_number != nullptr) << dlerror();
758   ASSERT_EQ(1729U, *taxicab_number);
759   *taxicab_number = 2;
760 
761   dlclose(handle);
762   ASSERT_TRUE(!is_unloaded);
763 
764   uint32_t* taxicab_number_after_dlclose = reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_nodelete_1_taxicab_number"));
765   ASSERT_EQ(taxicab_number_after_dlclose, taxicab_number);
766   ASSERT_EQ(2U, *taxicab_number_after_dlclose);
767 
768 
769   handle = dlopen("libtest_nodelete_1.so", RTLD_NOW);
770   uint32_t* taxicab_number2 = reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_nodelete_1_taxicab_number"));
771   ASSERT_EQ(taxicab_number2, taxicab_number);
772 
773   ASSERT_EQ(2U, *taxicab_number2);
774 
775   dlclose(handle);
776   ASSERT_TRUE(!is_unloaded);
777 }
778 
TEST(dlfcn,dlopen_nodelete_on_second_dlopen)779 TEST(dlfcn, dlopen_nodelete_on_second_dlopen) {
780   static bool is_unloaded = false;
781 
782   void* handle = dlopen("libtest_nodelete_2.so", RTLD_NOW);
783   ASSERT_TRUE(handle != nullptr) << dlerror();
784   void (*set_unload_flag_ptr)(bool*);
785   set_unload_flag_ptr = reinterpret_cast<void (*)(bool*)>(dlsym(handle, "dlopen_nodelete_2_set_unload_flag_ptr"));
786   ASSERT_TRUE(set_unload_flag_ptr != nullptr) << dlerror();
787   set_unload_flag_ptr(&is_unloaded);
788 
789   uint32_t* taxicab_number = reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_nodelete_2_taxicab_number"));
790   ASSERT_TRUE(taxicab_number != nullptr) << dlerror();
791 
792   ASSERT_EQ(1729U, *taxicab_number);
793   *taxicab_number = 2;
794 
795   // This RTLD_NODELETE should be ignored
796   void* handle1 = dlopen("libtest_nodelete_2.so", RTLD_NOW | RTLD_NODELETE);
797   ASSERT_TRUE(handle1 != nullptr) << dlerror();
798   ASSERT_EQ(handle, handle1);
799 
800   dlclose(handle1);
801   dlclose(handle);
802 
803   ASSERT_TRUE(is_unloaded);
804 }
805 
TEST(dlfcn,dlopen_nodelete_dt_flags_1)806 TEST(dlfcn, dlopen_nodelete_dt_flags_1) {
807   static bool is_unloaded = false;
808 
809   void* handle = dlopen("libtest_nodelete_dt_flags_1.so", RTLD_NOW);
810   ASSERT_TRUE(handle != nullptr) << dlerror();
811   void (*set_unload_flag_ptr)(bool*);
812   set_unload_flag_ptr = reinterpret_cast<void (*)(bool*)>(dlsym(handle, "dlopen_nodelete_dt_flags_1_set_unload_flag_ptr"));
813   ASSERT_TRUE(set_unload_flag_ptr != nullptr) << dlerror();
814   set_unload_flag_ptr(&is_unloaded);
815 
816   dlclose(handle);
817   ASSERT_TRUE(!is_unloaded);
818 }
819 
TEST(dlfcn,dlsym_df_1_global)820 TEST(dlfcn, dlsym_df_1_global) {
821   void* handle = dlopen("libtest_dlsym_df_1_global.so", RTLD_NOW);
822   ASSERT_TRUE(handle != nullptr) << dlerror();
823   int (*get_answer)();
824   get_answer = reinterpret_cast<int (*)()>(dlsym(handle, "dl_df_1_global_get_answer"));
825   ASSERT_TRUE(get_answer != nullptr) << dlerror();
826   ASSERT_EQ(42, get_answer());
827   ASSERT_EQ(0, dlclose(handle));
828 }
829 
TEST(dlfcn,dlopen_failure)830 TEST(dlfcn, dlopen_failure) {
831   void* self = dlopen("/does/not/exist", RTLD_NOW);
832   ASSERT_TRUE(self == nullptr);
833 #if defined(__BIONIC__)
834   ASSERT_STREQ("dlopen failed: library \"/does/not/exist\" not found", dlerror());
835 #else
836   ASSERT_STREQ("/does/not/exist: cannot open shared object file: No such file or directory", dlerror());
837 #endif
838 }
839 
TEST(dlfcn,dlclose_unload)840 TEST(dlfcn, dlclose_unload) {
841   void* handle = dlopen("libtest_simple.so", RTLD_NOW);
842   ASSERT_TRUE(handle != nullptr) << dlerror();
843   uint32_t* taxicab_number = static_cast<uint32_t*>(dlsym(handle, "dlopen_testlib_taxicab_number"));
844   ASSERT_TRUE(taxicab_number != nullptr) << dlerror();
845   EXPECT_EQ(1729U, *taxicab_number);
846   dlclose(handle);
847   // Making sure that the library has been unmapped as part of library unload
848   // process. Note that mprotect somewhat counter-intuitively returns ENOMEM in
849   // this case.
850   uintptr_t page_start = reinterpret_cast<uintptr_t>(taxicab_number) & ~(PAGE_SIZE - 1);
851   ASSERT_TRUE(mprotect(reinterpret_cast<void*>(page_start), PAGE_SIZE, PROT_NONE) != 0);
852   ASSERT_EQ(ENOMEM, errno) << strerror(errno);
853 }
854 
ConcurrentDlErrorFn(std::string & error)855 static void ConcurrentDlErrorFn(std::string& error) {
856   ASSERT_TRUE(dlerror() == nullptr);
857 
858   void* handle = dlopen("/child/thread", RTLD_NOW);
859   ASSERT_TRUE(handle == nullptr);
860 
861   const char* err = dlerror();
862   ASSERT_TRUE(err != nullptr);
863 
864   error = err;
865 }
866 
TEST(dlfcn,dlerror_concurrent_buffer)867 TEST(dlfcn, dlerror_concurrent_buffer) {
868   void* handle = dlopen("/main/thread", RTLD_NOW);
869   ASSERT_TRUE(handle == nullptr);
870   const char* main_thread_error = dlerror();
871   ASSERT_TRUE(main_thread_error != nullptr);
872   ASSERT_SUBSTR("/main/thread", main_thread_error);
873 
874   std::string child_thread_error;
875   std::thread t(ConcurrentDlErrorFn, std::ref(child_thread_error));
876   t.join();
877   ASSERT_SUBSTR("/child/thread", child_thread_error.c_str());
878 
879   // Check that main thread local buffer was not modified.
880   ASSERT_SUBSTR("/main/thread", main_thread_error);
881 }
882 
TEST(dlfcn,dlerror_concurrent)883 TEST(dlfcn, dlerror_concurrent) {
884   void* handle = dlopen("/main/thread", RTLD_NOW);
885   ASSERT_TRUE(handle == nullptr);
886 
887   std::string child_thread_error;
888   std::thread t(ConcurrentDlErrorFn, std::ref(child_thread_error));
889   t.join();
890   ASSERT_SUBSTR("/child/thread", child_thread_error.c_str());
891 
892   const char* main_thread_error = dlerror();
893   ASSERT_TRUE(main_thread_error != nullptr);
894   ASSERT_SUBSTR("/main/thread", main_thread_error);
895 }
896 
TEST(dlfcn,dlsym_failures)897 TEST(dlfcn, dlsym_failures) {
898   dlerror(); // Clear any pending errors.
899   void* self = dlopen(nullptr, RTLD_NOW);
900   ASSERT_TRUE(self != nullptr);
901   ASSERT_TRUE(dlerror() == nullptr);
902 
903   void* sym;
904 
905 #if defined(__BIONIC__) && !defined(__LP64__)
906   // RTLD_DEFAULT in lp32 bionic is not (void*)0
907   // so it can be distinguished from the NULL handle.
908   sym = dlsym(nullptr, "test");
909   ASSERT_TRUE(sym == nullptr);
910   ASSERT_STREQ("dlsym failed: library handle is null", dlerror());
911 #endif
912 
913   // Symbol that doesn't exist.
914   sym = dlsym(self, "ThisSymbolDoesNotExist");
915   ASSERT_TRUE(sym == nullptr);
916   ASSERT_SUBSTR("undefined symbol: ThisSymbolDoesNotExist", dlerror());
917 
918   ASSERT_EQ(0, dlclose(self));
919 }
920 
TEST(dlfcn,dladdr_executable)921 TEST(dlfcn, dladdr_executable) {
922   dlerror(); // Clear any pending errors.
923   void* self = dlopen(nullptr, RTLD_NOW);
924   ASSERT_TRUE(self != nullptr);
925   ASSERT_TRUE(dlerror() == nullptr);
926 
927   void* sym = dlsym(self, "DlSymTestFunction");
928   ASSERT_TRUE(sym != nullptr);
929 
930   // Deliberately ask dladdr for an address inside a symbol, rather than the symbol base address.
931   void* addr = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(sym) + 2);
932 
933   Dl_info info;
934   int rc = dladdr(addr, &info);
935   ASSERT_NE(rc, 0); // Zero on error, non-zero on success.
936 
937   // Get the name of this executable.
938   const std::string executable_path = android::base::GetExecutablePath();
939 
940   // The filename should be that of this executable.
941   char dli_realpath[PATH_MAX];
942   ASSERT_TRUE(realpath(info.dli_fname, dli_realpath) != nullptr);
943   ASSERT_STREQ(executable_path.c_str(), dli_realpath);
944 
945   // The symbol name should be the symbol we looked up.
946   ASSERT_STREQ(info.dli_sname, "DlSymTestFunction");
947 
948   // The address should be the exact address of the symbol.
949   ASSERT_EQ(info.dli_saddr, sym);
950 
951   std::vector<map_record> maps;
952   ASSERT_TRUE(Maps::parse_maps(&maps));
953 
954   void* base_address = nullptr;
955   for (const map_record& rec : maps) {
956     if (executable_path == rec.pathname) {
957       base_address = reinterpret_cast<void*>(rec.addr_start);
958       break;
959     }
960   }
961 
962   // The base address should be the address we were loaded at.
963   ASSERT_EQ(info.dli_fbase, base_address);
964 
965   ASSERT_EQ(0, dlclose(self));
966 }
967 
TEST(dlfcn,dlopen_executable_by_absolute_path)968 TEST(dlfcn, dlopen_executable_by_absolute_path) {
969   void* handle1 = dlopen(nullptr, RTLD_NOW);
970   ASSERT_TRUE(handle1 != nullptr) << dlerror();
971 
972   void* handle2 = dlopen(android::base::GetExecutablePath().c_str(), RTLD_NOW);
973   ASSERT_TRUE(handle2 != nullptr) << dlerror();
974 
975 #if defined(__BIONIC__)
976   ASSERT_EQ(handle1, handle2);
977 #else
978   GTEST_SKIP() << "Skipping ASSERT_EQ(handle1, handle2) for glibc: "
979                   "it loads a separate copy of the main executable "
980                   "on dlopen by absolute path";
981 #endif
982 }
983 
984 #if defined (__aarch64__)
985 #define ALTERNATE_PATH_TO_SYSTEM_LIB "/system/lib/arm64/"
986 #elif defined (__arm__)
987 #define ALTERNATE_PATH_TO_SYSTEM_LIB "/system/lib/arm/"
988 #elif defined (__i386__)
989 #define ALTERNATE_PATH_TO_SYSTEM_LIB "/system/lib/x86/"
990 #elif defined (__x86_64__)
991 #define ALTERNATE_PATH_TO_SYSTEM_LIB "/system/lib/x86_64/"
992 #elif defined (__mips__)
993 #if defined(__LP64__)
994 #define ALTERNATE_PATH_TO_SYSTEM_LIB "/system/lib/mips64/"
995 #else
996 #define ALTERNATE_PATH_TO_SYSTEM_LIB "/system/lib/mips/"
997 #endif
998 #else
999 #error "Unknown architecture"
1000 #endif
1001 #define PATH_TO_LIBC PATH_TO_SYSTEM_LIB "libc.so"
1002 #define ALTERNATE_PATH_TO_LIBC ALTERNATE_PATH_TO_SYSTEM_LIB "libc.so"
1003 
TEST(dlfcn,dladdr_libc)1004 TEST(dlfcn, dladdr_libc) {
1005 #if defined(__GLIBC__)
1006   GTEST_SKIP() << "glibc returns libc.so's ldconfig path, which is a symlink (not a realpath)";
1007 #endif
1008 
1009   Dl_info info;
1010   void* addr = reinterpret_cast<void*>(puts); // well-known libc function
1011   ASSERT_TRUE(dladdr(addr, &info) != 0);
1012 
1013   char libc_realpath[PATH_MAX];
1014 
1015   // Check if libc is in canonical path or in alternate path.
1016   if (strncmp(ALTERNATE_PATH_TO_SYSTEM_LIB,
1017               info.dli_fname,
1018               sizeof(ALTERNATE_PATH_TO_SYSTEM_LIB) - 1) == 0) {
1019     // Platform with emulated architecture.  Symlink on ARC++.
1020     ASSERT_TRUE(realpath(ALTERNATE_PATH_TO_LIBC, libc_realpath) == libc_realpath);
1021   } else {
1022     // /system/lib is symlink when this test is executed on host.
1023     ASSERT_TRUE(realpath(PATH_TO_LIBC, libc_realpath) == libc_realpath);
1024   }
1025 
1026   ASSERT_STREQ(libc_realpath, info.dli_fname);
1027   // TODO: add check for dfi_fbase
1028   ASSERT_STREQ("puts", info.dli_sname);
1029   ASSERT_EQ(addr, info.dli_saddr);
1030 }
1031 
TEST(dlfcn,dladdr_invalid)1032 TEST(dlfcn, dladdr_invalid) {
1033   Dl_info info;
1034 
1035   dlerror(); // Clear any pending errors.
1036 
1037   // No symbol corresponding to NULL.
1038   ASSERT_EQ(dladdr(nullptr, &info), 0); // Zero on error, non-zero on success.
1039   ASSERT_TRUE(dlerror() == nullptr); // dladdr(3) doesn't set dlerror(3).
1040 
1041   // No symbol corresponding to a stack address.
1042   ASSERT_EQ(dladdr(&info, &info), 0); // Zero on error, non-zero on success.
1043   ASSERT_TRUE(dlerror() == nullptr); // dladdr(3) doesn't set dlerror(3).
1044 }
1045 
1046 // GNU-style ELF hash tables are incompatible with the MIPS ABI.
1047 // MIPS requires .dynsym to be sorted to match the GOT but GNU-style requires sorting by hash code.
TEST(dlfcn,dlopen_library_with_only_gnu_hash)1048 TEST(dlfcn, dlopen_library_with_only_gnu_hash) {
1049 #if !defined(__mips__)
1050   dlerror(); // Clear any pending errors.
1051   void* handle = dlopen("libgnu-hash-table-library.so", RTLD_NOW);
1052   ASSERT_TRUE(handle != nullptr) << dlerror();
1053   auto guard = android::base::make_scope_guard([&]() { dlclose(handle); });
1054   void* sym = dlsym(handle, "getRandomNumber");
1055   ASSERT_TRUE(sym != nullptr) << dlerror();
1056   int (*fn)(void);
1057   fn = reinterpret_cast<int (*)(void)>(sym);
1058   EXPECT_EQ(4, fn());
1059 
1060   Dl_info dlinfo;
1061   ASSERT_TRUE(0 != dladdr(reinterpret_cast<void*>(fn), &dlinfo));
1062 
1063   ASSERT_TRUE(fn == dlinfo.dli_saddr);
1064   ASSERT_STREQ("getRandomNumber", dlinfo.dli_sname);
1065   ASSERT_SUBSTR("libgnu-hash-table-library.so", dlinfo.dli_fname);
1066 #else
1067   GTEST_SKIP() << "mips toolchain does not support '--hash-style=gnu'";
1068 #endif
1069 }
1070 
TEST(dlfcn,dlopen_library_with_only_sysv_hash)1071 TEST(dlfcn, dlopen_library_with_only_sysv_hash) {
1072   void* handle = dlopen("libsysv-hash-table-library.so", RTLD_NOW);
1073   ASSERT_TRUE(handle != nullptr) << dlerror();
1074   auto guard = android::base::make_scope_guard([&]() { dlclose(handle); });
1075   void* sym = dlsym(handle, "getRandomNumber");
1076   ASSERT_TRUE(sym != nullptr) << dlerror();
1077   int (*fn)(void);
1078   fn = reinterpret_cast<int (*)(void)>(sym);
1079   EXPECT_EQ(4, fn());
1080 
1081   Dl_info dlinfo;
1082   ASSERT_TRUE(0 != dladdr(reinterpret_cast<void*>(fn), &dlinfo));
1083 
1084   ASSERT_TRUE(fn == dlinfo.dli_saddr);
1085   ASSERT_STREQ("getRandomNumber", dlinfo.dli_sname);
1086   ASSERT_SUBSTR("libsysv-hash-table-library.so", dlinfo.dli_fname);
1087 }
1088 
TEST(dlfcn,dlopen_bad_flags)1089 TEST(dlfcn, dlopen_bad_flags) {
1090   dlerror(); // Clear any pending errors.
1091   void* handle;
1092 
1093 #if defined(__GLIBC__)
1094   // glibc was smart enough not to define RTLD_NOW as 0, so it can detect missing flags.
1095   handle = dlopen(nullptr, 0);
1096   ASSERT_TRUE(handle == nullptr);
1097   ASSERT_SUBSTR("invalid", dlerror());
1098 #endif
1099 
1100   handle = dlopen(nullptr, 0xffffffff);
1101   ASSERT_TRUE(handle == nullptr);
1102   ASSERT_SUBSTR("invalid", dlerror());
1103 
1104   // glibc actually allows you to choose both RTLD_NOW and RTLD_LAZY at the same time, and so do we.
1105   handle = dlopen(nullptr, RTLD_NOW|RTLD_LAZY);
1106   ASSERT_TRUE(handle != nullptr);
1107   ASSERT_SUBSTR(nullptr, dlerror());
1108 }
1109 
TEST(dlfcn,rtld_default_unknown_symbol)1110 TEST(dlfcn, rtld_default_unknown_symbol) {
1111   void* addr = dlsym(RTLD_DEFAULT, "ANY_UNKNOWN_SYMBOL_NAME");
1112   ASSERT_TRUE(addr == nullptr);
1113 }
1114 
TEST(dlfcn,rtld_default_known_symbol)1115 TEST(dlfcn, rtld_default_known_symbol) {
1116   void* addr = dlsym(RTLD_DEFAULT, "fopen");
1117   ASSERT_TRUE(addr != nullptr);
1118 }
1119 
TEST(dlfcn,rtld_next_unknown_symbol)1120 TEST(dlfcn, rtld_next_unknown_symbol) {
1121   void* addr = dlsym(RTLD_NEXT, "ANY_UNKNOWN_SYMBOL_NAME");
1122   ASSERT_TRUE(addr == nullptr);
1123 }
1124 
TEST(dlfcn,rtld_next_known_symbol)1125 TEST(dlfcn, rtld_next_known_symbol) {
1126   void* addr = dlsym(RTLD_NEXT, "fopen");
1127   ASSERT_TRUE(addr != nullptr);
1128 }
1129 
1130 // Check that RTLD_NEXT of a libc symbol works in dlopened library
TEST(dlfcn,rtld_next_from_library)1131 TEST(dlfcn, rtld_next_from_library) {
1132   void* library_with_fclose = dlopen("libtest_check_rtld_next_from_library.so", RTLD_NOW | RTLD_GLOBAL);
1133   ASSERT_TRUE(library_with_fclose != nullptr) << dlerror();
1134   void* expected_addr = dlsym(RTLD_DEFAULT, "fclose");
1135   ASSERT_TRUE(expected_addr != nullptr) << dlerror();
1136   typedef void* (*get_libc_fclose_ptr_fn_t)();
1137   get_libc_fclose_ptr_fn_t get_libc_fclose_ptr =
1138       reinterpret_cast<get_libc_fclose_ptr_fn_t>(dlsym(library_with_fclose, "get_libc_fclose_ptr"));
1139   ASSERT_TRUE(get_libc_fclose_ptr != nullptr) << dlerror();
1140   ASSERT_EQ(expected_addr, get_libc_fclose_ptr());
1141 
1142   dlclose(library_with_fclose);
1143 }
1144 
1145 
TEST(dlfcn,dlsym_weak_func)1146 TEST(dlfcn, dlsym_weak_func) {
1147   dlerror();
1148   void* handle = dlopen("libtest_dlsym_weak_func.so", RTLD_NOW);
1149   ASSERT_TRUE(handle != nullptr);
1150 
1151   int (*weak_func)();
1152   weak_func = reinterpret_cast<int (*)()>(dlsym(handle, "weak_func"));
1153   ASSERT_TRUE(weak_func != nullptr) << "dlerror: " << dlerror();
1154   EXPECT_EQ(42, weak_func());
1155   dlclose(handle);
1156 }
1157 
TEST(dlfcn,dlopen_undefined_weak_func)1158 TEST(dlfcn, dlopen_undefined_weak_func) {
1159   void* handle = dlopen("libtest_dlopen_weak_undefined_func.so", RTLD_NOW);
1160   ASSERT_TRUE(handle != nullptr) << dlerror();
1161   int (*weak_func)();
1162   weak_func = reinterpret_cast<int (*)()>(dlsym(handle, "use_weak_undefined_func"));
1163   ASSERT_TRUE(weak_func != nullptr) << dlerror();
1164   EXPECT_EQ(6551, weak_func());
1165   dlclose(handle);
1166 }
1167 
TEST(dlfcn,dlopen_symlink)1168 TEST(dlfcn, dlopen_symlink) {
1169   DlfcnSymlink symlink("dlopen_symlink");
1170   const std::string symlink_name = basename(symlink.get_symlink_path().c_str());
1171   void* handle1 = dlopen("libdlext_test.so", RTLD_NOW);
1172   void* handle2 = dlopen(symlink_name.c_str(), RTLD_NOW);
1173   ASSERT_TRUE(handle1 != nullptr);
1174   ASSERT_TRUE(handle2 != nullptr);
1175   ASSERT_EQ(handle1, handle2);
1176   dlclose(handle1);
1177   dlclose(handle2);
1178 }
1179 
1180 // libtest_dlopen_from_ctor_main.so depends on
1181 // libtest_dlopen_from_ctor.so which has a constructor
1182 // that calls dlopen(libc...). This is to test the situation
1183 // described in b/7941716.
TEST(dlfcn,dlopen_dlopen_from_ctor)1184 TEST(dlfcn, dlopen_dlopen_from_ctor) {
1185 #if defined(__GLIBC__)
1186   GTEST_SKIP() << "glibc segfaults if you try to call dlopen from a constructor";
1187 #endif
1188 
1189   void* handle = dlopen("libtest_dlopen_from_ctor_main.so", RTLD_NOW);
1190   ASSERT_TRUE(handle != nullptr) << dlerror();
1191   dlclose(handle);
1192 }
1193 
1194 static std::string g_fini_call_order_str;
1195 
register_fini_call(const char * s)1196 static void register_fini_call(const char* s) {
1197   g_fini_call_order_str += s;
1198 }
1199 
test_init_fini_call_order_for(const char * libname)1200 static void test_init_fini_call_order_for(const char* libname) {
1201   g_fini_call_order_str.clear();
1202   void* handle = dlopen(libname, RTLD_NOW);
1203   ASSERT_TRUE(handle != nullptr) << dlerror();
1204   typedef int (*get_init_order_number_t)();
1205   get_init_order_number_t get_init_order_number =
1206           reinterpret_cast<get_init_order_number_t>(dlsym(handle, "get_init_order_number"));
1207   ASSERT_EQ(321, get_init_order_number());
1208 
1209   typedef void (*set_fini_callback_t)(void (*f)(const char*));
1210   set_fini_callback_t set_fini_callback =
1211           reinterpret_cast<set_fini_callback_t>(dlsym(handle, "set_fini_callback"));
1212   set_fini_callback(register_fini_call);
1213   dlclose(handle);
1214   ASSERT_EQ("(root)(child)(grandchild)", g_fini_call_order_str);
1215 }
1216 
TEST(dlfcn,init_fini_call_order)1217 TEST(dlfcn, init_fini_call_order) {
1218   test_init_fini_call_order_for("libtest_init_fini_order_root.so");
1219   test_init_fini_call_order_for("libtest_init_fini_order_root2.so");
1220 }
1221 
TEST(dlfcn,symbol_versioning_use_v1)1222 TEST(dlfcn, symbol_versioning_use_v1) {
1223   void* handle = dlopen("libtest_versioned_uselibv1.so", RTLD_NOW);
1224   ASSERT_TRUE(handle != nullptr) << dlerror();
1225   typedef int (*fn_t)();
1226   fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "get_function_version"));
1227   ASSERT_TRUE(fn != nullptr) << dlerror();
1228   ASSERT_EQ(1, fn());
1229   dlclose(handle);
1230 }
1231 
TEST(dlfcn,symbol_versioning_use_v2)1232 TEST(dlfcn, symbol_versioning_use_v2) {
1233   void* handle = dlopen("libtest_versioned_uselibv2.so", RTLD_NOW);
1234   ASSERT_TRUE(handle != nullptr) << dlerror();
1235   typedef int (*fn_t)();
1236   fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "get_function_version"));
1237   ASSERT_TRUE(fn != nullptr) << dlerror();
1238   ASSERT_EQ(2, fn());
1239   dlclose(handle);
1240 }
1241 
TEST(dlfcn,symbol_versioning_use_other_v2)1242 TEST(dlfcn, symbol_versioning_use_other_v2) {
1243   void* handle = dlopen("libtest_versioned_uselibv2_other.so", RTLD_NOW);
1244   ASSERT_TRUE(handle != nullptr) << dlerror();
1245   typedef int (*fn_t)();
1246   fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "get_function_version"));
1247   ASSERT_TRUE(fn != nullptr) << dlerror();
1248   ASSERT_EQ(20, fn());
1249   dlclose(handle);
1250 }
1251 
TEST(dlfcn,symbol_versioning_use_other_v3)1252 TEST(dlfcn, symbol_versioning_use_other_v3) {
1253   void* handle = dlopen("libtest_versioned_uselibv3_other.so", RTLD_NOW);
1254   ASSERT_TRUE(handle != nullptr) << dlerror();
1255   typedef int (*fn_t)();
1256   fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "get_function_version"));
1257   ASSERT_TRUE(fn != nullptr) << dlerror();
1258   ASSERT_EQ(3, fn());
1259   dlclose(handle);
1260 }
1261 
TEST(dlfcn,symbol_versioning_default_via_dlsym)1262 TEST(dlfcn, symbol_versioning_default_via_dlsym) {
1263   void* handle = dlopen("libtest_versioned_lib.so", RTLD_NOW);
1264   ASSERT_TRUE(handle != nullptr) << dlerror();
1265   typedef int (*fn_t)();
1266   fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "versioned_function"));
1267   ASSERT_TRUE(fn != nullptr) << dlerror();
1268   ASSERT_EQ(3, fn()); // the default version is 3
1269   dlclose(handle);
1270 }
1271 
TEST(dlfcn,dlvsym_smoke)1272 TEST(dlfcn, dlvsym_smoke) {
1273   void* handle = dlopen("libtest_versioned_lib.so", RTLD_NOW);
1274   ASSERT_TRUE(handle != nullptr) << dlerror();
1275   typedef int (*fn_t)();
1276 
1277   {
1278     fn_t fn = reinterpret_cast<fn_t>(dlvsym(handle, "versioned_function", "nonversion"));
1279     ASSERT_TRUE(fn == nullptr);
1280     ASSERT_SUBSTR("undefined symbol: versioned_function, version nonversion", dlerror());
1281   }
1282 
1283   {
1284     fn_t fn = reinterpret_cast<fn_t>(dlvsym(handle, "versioned_function", "TESTLIB_V2"));
1285     ASSERT_TRUE(fn != nullptr) << dlerror();
1286     ASSERT_EQ(2, fn());
1287   }
1288 
1289   dlclose(handle);
1290 }
1291 
1292 // This preempts the implementation from libtest_versioned_lib.so
version_zero_function()1293 extern "C" int version_zero_function() {
1294   return 0;
1295 }
1296 
1297 // This preempts the implementation from libtest_versioned_uselibv*.so
version_zero_function2()1298 extern "C" int version_zero_function2() {
1299   return 0;
1300 }
1301 
TEST(dlfcn,dt_runpath_smoke)1302 TEST(dlfcn, dt_runpath_smoke) {
1303   void* handle = dlopen("libtest_dt_runpath_d.so", RTLD_NOW);
1304   ASSERT_TRUE(handle != nullptr) << dlerror();
1305 
1306   typedef void *(* dlopen_b_fn)();
1307   dlopen_b_fn fn = (dlopen_b_fn)dlsym(handle, "dlopen_b");
1308   ASSERT_TRUE(fn != nullptr) << dlerror();
1309 
1310   void *p = fn();
1311   ASSERT_TRUE(p != nullptr);
1312 
1313   dlclose(handle);
1314 }
1315 
TEST(dlfcn,dt_runpath_absolute_path)1316 TEST(dlfcn, dt_runpath_absolute_path) {
1317   std::string libpath = GetTestlibRoot() + "/libtest_dt_runpath_d.so";
1318   void* handle = dlopen(libpath.c_str(), RTLD_NOW);
1319   ASSERT_TRUE(handle != nullptr) << dlerror();
1320 
1321   typedef void *(* dlopen_b_fn)();
1322   dlopen_b_fn fn = (dlopen_b_fn)dlsym(handle, "dlopen_b");
1323   ASSERT_TRUE(fn != nullptr) << dlerror();
1324 
1325   void *p = fn();
1326   ASSERT_TRUE(p != nullptr);
1327 
1328   dlclose(handle);
1329 }
1330 
test_dlclose_after_thread_local_dtor(const char * library_name)1331 static void test_dlclose_after_thread_local_dtor(const char* library_name) {
1332   bool is_dtor_triggered = false;
1333 
1334   auto f = [](void* handle, bool* is_dtor_triggered) {
1335     typedef void (*fn_t)(bool*);
1336     fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "init_thread_local_variable"));
1337     ASSERT_TRUE(fn != nullptr) << dlerror();
1338 
1339     fn(is_dtor_triggered);
1340 
1341     ASSERT_TRUE(!*is_dtor_triggered);
1342   };
1343 
1344   void* handle = dlopen(library_name, RTLD_NOW | RTLD_NOLOAD);
1345   ASSERT_TRUE(handle == nullptr);
1346 
1347   handle = dlopen(library_name, RTLD_NOW);
1348   ASSERT_TRUE(handle != nullptr) << dlerror();
1349 
1350   std::thread t(f, handle, &is_dtor_triggered);
1351   t.join();
1352 
1353   ASSERT_TRUE(is_dtor_triggered);
1354   dlclose(handle);
1355 
1356   handle = dlopen(library_name, RTLD_NOW | RTLD_NOLOAD);
1357   ASSERT_TRUE(handle == nullptr);
1358 }
1359 
TEST(dlfcn,dlclose_after_thread_local_dtor)1360 TEST(dlfcn, dlclose_after_thread_local_dtor) {
1361   test_dlclose_after_thread_local_dtor("libtest_thread_local_dtor.so");
1362 }
1363 
TEST(dlfcn,dlclose_after_thread_local_dtor_indirect)1364 TEST(dlfcn, dlclose_after_thread_local_dtor_indirect) {
1365   test_dlclose_after_thread_local_dtor("libtest_indirect_thread_local_dtor.so");
1366 }
1367 
test_dlclose_before_thread_local_dtor(const char * library_name)1368 static void test_dlclose_before_thread_local_dtor(const char* library_name) {
1369   bool is_dtor_triggered = false;
1370 
1371   auto f = [library_name](bool* is_dtor_triggered) {
1372     void* handle = dlopen(library_name, RTLD_NOW | RTLD_NOLOAD);
1373     ASSERT_TRUE(handle == nullptr);
1374 
1375     handle = dlopen(library_name, RTLD_NOW);
1376     ASSERT_TRUE(handle != nullptr) << dlerror();
1377 
1378     typedef void (*fn_t)(bool*);
1379     fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "init_thread_local_variable"));
1380     ASSERT_TRUE(fn != nullptr) << dlerror();
1381 
1382     fn(is_dtor_triggered);
1383 
1384     dlclose(handle);
1385 
1386     ASSERT_TRUE(!*is_dtor_triggered);
1387 
1388     // Since we have thread_atexit dtors associated with handle - the library should
1389     // still be availabe.
1390     handle = dlopen(library_name, RTLD_NOW | RTLD_NOLOAD);
1391     ASSERT_TRUE(handle != nullptr) << dlerror();
1392     dlclose(handle);
1393   };
1394 
1395   void* handle = dlopen(library_name, RTLD_NOW);
1396   ASSERT_TRUE(handle != nullptr) << dlerror();
1397   dlclose(handle);
1398 
1399   handle = dlopen(library_name, RTLD_NOW | RTLD_NOLOAD);
1400   ASSERT_TRUE(handle == nullptr);
1401 
1402   std::thread t(f, &is_dtor_triggered);
1403   t.join();
1404 #if defined(__BIONIC__)
1405   // ld-android.so unloads unreferenced libraries on pthread_exit()
1406   ASSERT_TRUE(is_dtor_triggered);
1407   handle = dlopen(library_name, RTLD_NOW | RTLD_NOLOAD);
1408   ASSERT_TRUE(handle == nullptr);
1409 #else
1410   // GLIBC does not unload libraries with ref_count = 0 on pthread_exit
1411   ASSERT_TRUE(is_dtor_triggered);
1412   handle = dlopen(library_name, RTLD_NOW | RTLD_NOLOAD);
1413   ASSERT_TRUE(handle != nullptr) << dlerror();
1414 #endif
1415 }
1416 
TEST(dlfcn,dlclose_before_thread_local_dtor)1417 TEST(dlfcn, dlclose_before_thread_local_dtor) {
1418   test_dlclose_before_thread_local_dtor("libtest_thread_local_dtor.so");
1419 }
1420 
TEST(dlfcn,dlclose_before_thread_local_dtor_indirect)1421 TEST(dlfcn, dlclose_before_thread_local_dtor_indirect) {
1422   test_dlclose_before_thread_local_dtor("libtest_indirect_thread_local_dtor.so");
1423 }
1424 
TEST(dlfcn,dlclose_before_thread_local_dtor_multiple_dsos)1425 TEST(dlfcn, dlclose_before_thread_local_dtor_multiple_dsos) {
1426   const constexpr char* library_name = "libtest_indirect_thread_local_dtor.so";
1427 
1428   bool is_dtor1_triggered = false;
1429   bool is_dtor2_triggered = false;
1430 
1431   std::mutex mtx;
1432   std::condition_variable cv;
1433   void* library_handle = nullptr;
1434   bool thread1_dlopen_complete = false;
1435   bool thread2_thread_local_dtor_initialized = false;
1436   bool thread1_complete = false;
1437 
1438   auto f1 = [&]() {
1439     void* handle = dlopen(library_name, RTLD_NOW | RTLD_NOLOAD);
1440     ASSERT_TRUE(handle == nullptr);
1441 
1442     handle = dlopen(library_name, RTLD_NOW);
1443     ASSERT_TRUE(handle != nullptr) << dlerror();
1444     std::unique_lock<std::mutex> lock(mtx);
1445     thread1_dlopen_complete = true;
1446     library_handle = handle;
1447     lock.unlock();
1448     cv.notify_one();
1449 
1450     typedef void (*fn_t)(bool*);
1451     fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "init_thread_local_variable"));
1452     ASSERT_TRUE(fn != nullptr) << dlerror();
1453 
1454     fn(&is_dtor1_triggered);
1455 
1456     lock.lock();
1457     cv.wait(lock, [&] { return thread2_thread_local_dtor_initialized; });
1458     lock.unlock();
1459 
1460     dlclose(handle);
1461 
1462     ASSERT_TRUE(!is_dtor1_triggered);
1463 
1464     // Since we have thread_atexit dtors associated with handle - the library should
1465     // still be availabe.
1466     handle = dlopen(library_name, RTLD_NOW | RTLD_NOLOAD);
1467     ASSERT_TRUE(handle != nullptr) << dlerror();
1468     dlclose(handle);
1469   };
1470 
1471   auto f2 = [&]() {
1472     std::unique_lock<std::mutex> lock(mtx);
1473     cv.wait(lock, [&] { return thread1_dlopen_complete; });
1474     void* handle = library_handle;
1475     lock.unlock();
1476 
1477     typedef void (*fn_t)(bool*);
1478     fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "init_thread_local_variable2"));
1479     ASSERT_TRUE(fn != nullptr) << dlerror();
1480 
1481     fn(&is_dtor2_triggered);
1482 
1483     lock.lock();
1484     thread2_thread_local_dtor_initialized = true;
1485     lock.unlock();
1486     cv.notify_one();
1487 
1488     lock.lock();
1489     cv.wait(lock, [&] { return thread1_complete; });
1490     lock.unlock();
1491 
1492     ASSERT_TRUE(!is_dtor2_triggered);
1493   };
1494 
1495   void* handle = dlopen(library_name, RTLD_NOW);
1496   ASSERT_TRUE(handle != nullptr) << dlerror();
1497   dlclose(handle);
1498 
1499   handle = dlopen(library_name, RTLD_NOW | RTLD_NOLOAD);
1500   ASSERT_TRUE(handle == nullptr);
1501 
1502   std::thread t1(f1);
1503   std::thread t2(f2);
1504   t1.join();
1505   ASSERT_TRUE(is_dtor1_triggered);
1506   ASSERT_TRUE(!is_dtor2_triggered);
1507 
1508   handle = dlopen(library_name, RTLD_NOW | RTLD_NOLOAD);
1509   ASSERT_TRUE(handle != nullptr) << dlerror();
1510   dlclose(handle);
1511 
1512   std::unique_lock<std::mutex> lock(mtx);
1513   thread1_complete = true;
1514   lock.unlock();
1515   cv.notify_one();
1516 
1517   t2.join();
1518   ASSERT_TRUE(is_dtor2_triggered);
1519 
1520 #if defined(__BIONIC__)
1521   // ld-android.so unloads unreferenced libraries on pthread_exit()
1522   handle = dlopen(library_name, RTLD_NOW | RTLD_NOLOAD);
1523   ASSERT_TRUE(handle == nullptr);
1524 #else
1525   // GLIBC does not unload libraries with ref_count = 0 on pthread_exit
1526   handle = dlopen(library_name, RTLD_NOW | RTLD_NOLOAD);
1527   ASSERT_TRUE(handle != nullptr) << dlerror();
1528 #endif
1529 }
1530 
TEST(dlfcn,RTLD_macros)1531 TEST(dlfcn, RTLD_macros) {
1532 #if !defined(RTLD_LOCAL)
1533 #error no RTLD_LOCAL
1534 #elif !defined(RTLD_LAZY)
1535 #error no RTLD_LAZY
1536 #elif !defined(RTLD_NOW)
1537 #error no RTLD_NOW
1538 #elif !defined(RTLD_NOLOAD)
1539 #error no RTLD_NOLOAD
1540 #elif !defined(RTLD_GLOBAL)
1541 #error no RTLD_GLOBAL
1542 #elif !defined(RTLD_NODELETE)
1543 #error no RTLD_NODELETE
1544 #endif
1545 }
1546 
1547 // Bionic specific tests
1548 #if defined(__BIONIC__)
1549 
1550 #if defined(__arm__)
to_dynamic_table(const char * p)1551 const llvm::ELF::Elf32_Dyn* to_dynamic_table(const char* p) {
1552   return reinterpret_cast<const llvm::ELF::Elf32_Dyn*>(p);
1553 }
1554 
1555 // Duplicate these definitions here because they are android specific
1556 //  - note that we cannot include <elf.h> because #defines conflict with
1557 //    enum names provided by LLVM.
1558 //  - we also don't use llvm::ELF::DT_LOOS because its value is 0x60000000
1559 //    rather than the 0x6000000d we expect
1560 #define DT_LOOS 0x6000000d
1561 #define DT_ANDROID_REL (DT_LOOS + 2)
1562 #define DT_ANDROID_RELA (DT_LOOS + 4)
1563 
1564 template<typename ELFT>
validate_compatibility_of_native_library(const std::string & soname,const std::string & path,ELFT * elf)1565 void validate_compatibility_of_native_library(const std::string& soname,
1566                                               const std::string& path, ELFT* elf) {
1567   bool has_elf_hash = false;
1568   bool has_android_rel = false;
1569   bool has_rel = false;
1570   // Find dynamic section and check that DT_HASH and there is no DT_ANDROID_REL
1571   for (auto it = elf->section_begin(); it != elf->section_end(); ++it) {
1572     const llvm::object::ELFSectionRef& section_ref = *it;
1573     if (section_ref.getType() == llvm::ELF::SHT_DYNAMIC) {
1574       llvm::StringRef data;
1575       ASSERT_TRUE(!it->getContents(data)) << "unable to get SHT_DYNAMIC section data";
1576       for (auto d = to_dynamic_table(data.data()); d->d_tag != llvm::ELF::DT_NULL; ++d) {
1577         if (d->d_tag == llvm::ELF::DT_HASH) {
1578           has_elf_hash = true;
1579         } else if (d->d_tag == DT_ANDROID_REL || d->d_tag == DT_ANDROID_RELA) {
1580           has_android_rel = true;
1581         } else if (d->d_tag == llvm::ELF::DT_REL || d->d_tag == llvm::ELF::DT_RELA) {
1582           has_rel = true;
1583         }
1584       }
1585 
1586       break;
1587     }
1588   }
1589 
1590   ASSERT_TRUE(has_elf_hash) << path.c_str() << ": missing elf hash (DT_HASH)";
1591   ASSERT_TRUE(!has_android_rel) << path.c_str() << ": has packed relocations";
1592   // libdl.so is simple enough that it might not have any relocations, so
1593   // exempt it from the DT_REL/DT_RELA check.
1594   if (soname != "libdl.so") {
1595     ASSERT_TRUE(has_rel) << path.c_str() << ": missing DT_REL/DT_RELA";
1596   }
1597 }
1598 
validate_compatibility_of_native_library(const std::string & soname)1599 void validate_compatibility_of_native_library(const std::string& soname) {
1600   // On the systems with emulation system libraries would be of different
1601   // architecture.  Try to use alternate paths first.
1602   std::string path = std::string(ALTERNATE_PATH_TO_SYSTEM_LIB) + soname;
1603   auto binary_or_error = llvm::object::createBinary(path);
1604   if (!binary_or_error) {
1605     path = std::string(PATH_TO_SYSTEM_LIB) + soname;
1606     binary_or_error = llvm::object::createBinary(path);
1607   }
1608   ASSERT_FALSE(!binary_or_error);
1609 
1610   llvm::object::Binary* binary = binary_or_error.get().getBinary();
1611 
1612   auto obj = llvm::dyn_cast<llvm::object::ObjectFile>(binary);
1613   ASSERT_TRUE(obj != nullptr);
1614 
1615   auto elf = llvm::dyn_cast<llvm::object::ELF32LEObjectFile>(obj);
1616 
1617   ASSERT_TRUE(elf != nullptr);
1618 
1619   validate_compatibility_of_native_library(soname, path, elf);
1620 }
1621 
1622 // This is a test for app compatibility workaround for arm apps
1623 // affected by http://b/24465209
TEST(dlext,compat_elf_hash_and_relocation_tables)1624 TEST(dlext, compat_elf_hash_and_relocation_tables) {
1625   validate_compatibility_of_native_library("libc.so");
1626   validate_compatibility_of_native_library("liblog.so");
1627   validate_compatibility_of_native_library("libstdc++.so");
1628   validate_compatibility_of_native_library("libdl.so");
1629   validate_compatibility_of_native_library("libm.so");
1630   validate_compatibility_of_native_library("libz.so");
1631   validate_compatibility_of_native_library("libjnigraphics.so");
1632 }
1633 
1634 #endif //  defined(__arm__)
1635 
TEST(dlfcn,dlopen_invalid_rw_load_segment)1636 TEST(dlfcn, dlopen_invalid_rw_load_segment) {
1637   const std::string libpath = GetTestlibRoot() +
1638                               "/" + kPrebuiltElfDir +
1639                               "/libtest_invalid-rw_load_segment.so";
1640   void* handle = dlopen(libpath.c_str(), RTLD_NOW);
1641   ASSERT_TRUE(handle == nullptr);
1642   std::string expected_dlerror = std::string("dlopen failed: \"") + libpath + "\": W+E load segments are not allowed";
1643   ASSERT_STREQ(expected_dlerror.c_str(), dlerror());
1644 }
1645 
TEST(dlfcn,dlopen_invalid_unaligned_shdr_offset)1646 TEST(dlfcn, dlopen_invalid_unaligned_shdr_offset) {
1647   const std::string libpath = GetTestlibRoot() +
1648                               "/" + kPrebuiltElfDir +
1649                               "/libtest_invalid-unaligned_shdr_offset.so";
1650 
1651   void* handle = dlopen(libpath.c_str(), RTLD_NOW);
1652   ASSERT_TRUE(handle == nullptr);
1653   std::string expected_dlerror = std::string("dlopen failed: \"") + libpath + "\" has invalid shdr offset/size: ";
1654   ASSERT_SUBSTR(expected_dlerror.c_str(), dlerror());
1655 }
1656 
TEST(dlfcn,dlopen_invalid_zero_shentsize)1657 TEST(dlfcn, dlopen_invalid_zero_shentsize) {
1658   const std::string libpath = GetTestlibRoot() +
1659                               "/" + kPrebuiltElfDir +
1660                               "/libtest_invalid-zero_shentsize.so";
1661 
1662   void* handle = dlopen(libpath.c_str(), RTLD_NOW);
1663   ASSERT_TRUE(handle == nullptr);
1664   std::string expected_dlerror = std::string("dlopen failed: \"") + libpath + "\" has unsupported e_shentsize: 0x0 (expected 0x";
1665   ASSERT_SUBSTR(expected_dlerror.c_str(), dlerror());
1666 }
1667 
TEST(dlfcn,dlopen_invalid_zero_shstrndx)1668 TEST(dlfcn, dlopen_invalid_zero_shstrndx) {
1669   const std::string libpath = GetTestlibRoot() +
1670                               "/" + kPrebuiltElfDir +
1671                               "/libtest_invalid-zero_shstrndx.so";
1672 
1673   void* handle = dlopen(libpath.c_str(), RTLD_NOW);
1674   ASSERT_TRUE(handle == nullptr);
1675   std::string expected_dlerror = std::string("dlopen failed: \"") + libpath + "\" has invalid e_shstrndx";
1676   ASSERT_STREQ(expected_dlerror.c_str(), dlerror());
1677 }
1678 
TEST(dlfcn,dlopen_invalid_empty_shdr_table)1679 TEST(dlfcn, dlopen_invalid_empty_shdr_table) {
1680   const std::string libpath = GetTestlibRoot() +
1681                               "/" + kPrebuiltElfDir +
1682                               "/libtest_invalid-empty_shdr_table.so";
1683 
1684   void* handle = dlopen(libpath.c_str(), RTLD_NOW);
1685   ASSERT_TRUE(handle == nullptr);
1686   std::string expected_dlerror = std::string("dlopen failed: \"") + libpath + "\" has no section headers";
1687   ASSERT_STREQ(expected_dlerror.c_str(), dlerror());
1688 }
1689 
TEST(dlfcn,dlopen_invalid_zero_shdr_table_offset)1690 TEST(dlfcn, dlopen_invalid_zero_shdr_table_offset) {
1691   const std::string libpath = GetTestlibRoot() +
1692                               "/" + kPrebuiltElfDir +
1693                               "/libtest_invalid-zero_shdr_table_offset.so";
1694 
1695   void* handle = dlopen(libpath.c_str(), RTLD_NOW);
1696   ASSERT_TRUE(handle == nullptr);
1697   std::string expected_dlerror = std::string("dlopen failed: \"") + libpath + "\" has invalid shdr offset/size: 0/";
1698   ASSERT_SUBSTR(expected_dlerror.c_str(), dlerror());
1699 }
1700 
TEST(dlfcn,dlopen_invalid_zero_shdr_table_content)1701 TEST(dlfcn, dlopen_invalid_zero_shdr_table_content) {
1702   const std::string libpath = GetTestlibRoot() +
1703                               "/" + kPrebuiltElfDir +
1704                               "/libtest_invalid-zero_shdr_table_content.so";
1705 
1706   void* handle = dlopen(libpath.c_str(), RTLD_NOW);
1707   ASSERT_TRUE(handle == nullptr);
1708   std::string expected_dlerror = std::string("dlopen failed: \"") + libpath + "\" .dynamic section header was not found";
1709   ASSERT_SUBSTR(expected_dlerror.c_str(), dlerror());
1710 }
1711 
TEST(dlfcn,dlopen_invalid_textrels)1712 TEST(dlfcn, dlopen_invalid_textrels) {
1713   const std::string libpath = GetTestlibRoot() +
1714                               "/" + kPrebuiltElfDir +
1715                               "/libtest_invalid-textrels.so";
1716 
1717   void* handle = dlopen(libpath.c_str(), RTLD_NOW);
1718   ASSERT_TRUE(handle == nullptr);
1719   std::string expected_dlerror = std::string("dlopen failed: \"") + libpath + "\" has text relocations";
1720   ASSERT_SUBSTR(expected_dlerror.c_str(), dlerror());
1721 }
1722 
TEST(dlfcn,dlopen_invalid_textrels2)1723 TEST(dlfcn, dlopen_invalid_textrels2) {
1724   const std::string libpath = GetTestlibRoot() +
1725                               "/" + kPrebuiltElfDir +
1726                               "/libtest_invalid-textrels2.so";
1727 
1728   void* handle = dlopen(libpath.c_str(), RTLD_NOW);
1729   ASSERT_TRUE(handle == nullptr);
1730   std::string expected_dlerror = std::string("dlopen failed: \"") + libpath + "\" has text relocations";
1731   ASSERT_SUBSTR(expected_dlerror.c_str(), dlerror());
1732 }
1733 
TEST(dlfcn,dlopen_df_1_global)1734 TEST(dlfcn, dlopen_df_1_global) {
1735   void* handle = dlopen("libtest_dlopen_df_1_global.so", RTLD_NOW);
1736   ASSERT_TRUE(handle != nullptr) << dlerror();
1737 }
1738 
TEST(dlfcn,segment_gap)1739 TEST(dlfcn, segment_gap) {
1740   void* handle = dlopen("libsegment_gap_outer.so", RTLD_NOW);
1741   ASSERT_TRUE(handle != nullptr) << dlerror();
1742 
1743   auto get_inner = reinterpret_cast<void* (*)()>(dlsym(handle, "get_inner"));
1744   void* inner = get_inner();
1745   (void)inner;
1746 
1747 #if __arm__
1748   int count;
1749   _Unwind_Ptr outer_exidx = dl_unwind_find_exidx(reinterpret_cast<_Unwind_Ptr>(get_inner), &count);
1750   _Unwind_Ptr inner_exidx = dl_unwind_find_exidx(reinterpret_cast<_Unwind_Ptr>(inner), &count);
1751   EXPECT_NE(0u, outer_exidx);
1752   EXPECT_NE(0u, inner_exidx);
1753   EXPECT_NE(inner_exidx, outer_exidx);
1754 #endif
1755 
1756   Dl_info info;
1757   int rc = dladdr(inner, &info);
1758   ASSERT_NE(rc, 0);
1759 
1760   EXPECT_NE(nullptr, strstr(info.dli_fname, "libsegment_gap_inner.so"));
1761 }
1762 
1763 #endif
1764