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 #if defined(__BIONIC__)
20 #include <android-base/properties.h>
21 #endif
22 
23 #include <dlfcn.h>
24 #include <libgen.h>
25 #include <limits.h>
26 #include <stdio.h>
27 #include <stdint.h>
28 #include <sys/stat.h>
29 
30 #include <fstream>
31 #include <iostream>
32 #include <regex>
33 #include <string>
34 
35 #include <android-base/file.h>
36 #include <android-base/macros.h>
37 #include <android-base/test_utils.h>
38 #include "gtest_globals.h"
39 #include "utils.h"
40 
main_global_default_serial()41 extern "C" int main_global_default_serial() {
42   return 3370318;
43 }
44 
main_global_protected_serial()45 extern "C" int main_global_protected_serial() {
46   return 2716057;
47 }
48 
49 // The following functions are defined in DT_NEEDED
50 // libdl_preempt_test.so library.
51 
52 // This one calls main_global_default_serial
53 extern "C" int main_global_default_get_serial();
54 
55 // This one calls main_global_protected_serial
56 extern "C" int main_global_protected_get_serial();
57 
58 // This one calls lib_global_default_serial
59 extern "C" int lib_global_default_get_serial();
60 
61 // This one calls lib_global_protected_serial
62 extern "C" int lib_global_protected_get_serial();
63 
64 // This test verifies that the global default function
65 // main_global_default_serial() is preempted by
66 // the function defined above.
TEST(dl,main_preempts_global_default)67 TEST(dl, main_preempts_global_default) {
68   ASSERT_EQ(3370318, main_global_default_get_serial());
69 }
70 
71 // This one makes sure that the global protected
72 // symbols do not get preempted
TEST(dl,main_does_not_preempt_global_protected)73 TEST(dl, main_does_not_preempt_global_protected) {
74   ASSERT_EQ(3370318, main_global_protected_get_serial());
75 }
76 
77 // check same things for lib
TEST(dl,lib_preempts_global_default)78 TEST(dl, lib_preempts_global_default) {
79   ASSERT_EQ(3370318, lib_global_default_get_serial());
80 }
81 
TEST(dl,lib_does_not_preempt_global_protected)82 TEST(dl, lib_does_not_preempt_global_protected) {
83   ASSERT_EQ(3370318, lib_global_protected_get_serial());
84 }
85 
86 #if defined(__BIONIC__)
87 #if defined(__LP64__)
88 #define LINKER_NAME "linker64"
89 #else
90 #define LINKER_NAME "linker"
91 #endif
92 static constexpr const char* kPathToLinker = "/system/bin/" LINKER_NAME;
93 static constexpr const char* kAlternatePathToLinker = "/system/bin/" ABI_STRING "/" LINKER_NAME;
94 #undef LINKER_NAME
95 
PathToLinker()96 const char* PathToLinker() {
97   // On the systems with emulated architecture linker would be of different
98   // architecture. Try to use alternate paths first.
99   struct stat buffer;
100   if (stat(kAlternatePathToLinker, &buffer) == 0) {
101     return kAlternatePathToLinker;
102   }
103   return kPathToLinker;
104 }
105 #endif  // defined(__BIONIC__)
106 
TEST(dl,exec_linker)107 TEST(dl, exec_linker) {
108 #if defined(__BIONIC__)
109   const char* path_to_linker = PathToLinker();
110   std::string usage_prefix = std::string("Usage: ") + path_to_linker;
111   ExecTestHelper eth;
112   eth.SetArgs({ path_to_linker, nullptr });
113   eth.Run([&]() { execve(path_to_linker, eth.GetArgs(), eth.GetEnv()); }, 0, nullptr);
114   ASSERT_EQ(0u, eth.GetOutput().find(usage_prefix)) << "Test output:\n" << eth.GetOutput();
115 #endif
116 }
117 
TEST(dl,exec_linker_load_file)118 TEST(dl, exec_linker_load_file) {
119 #if defined(__BIONIC__)
120   const char* path_to_linker = PathToLinker();
121   std::string helper = GetTestLibRoot() + "/exec_linker_helper";
122   std::string expected_output =
123       "ctor: argc=1 argv[0]=" + helper + "\n" +
124       "main: argc=1 argv[0]=" + helper + "\n" +
125       "__progname=exec_linker_helper\n" +
126       "helper_func called\n";
127   ExecTestHelper eth;
128   eth.SetArgs({ path_to_linker, helper.c_str(), nullptr });
129   eth.Run([&]() { execve(path_to_linker, eth.GetArgs(), eth.GetEnv()); }, 0, nullptr);
130   ASSERT_EQ(expected_output, eth.GetOutput());
131 #endif
132 }
133 
TEST(dl,exec_linker_load_from_zip)134 TEST(dl, exec_linker_load_from_zip) {
135 #if defined(__BIONIC__)
136   const char* path_to_linker = PathToLinker();
137   std::string helper = GetTestLibRoot() +
138       "/libdlext_test_zip/libdlext_test_zip_zipaligned.zip!/libdir/exec_linker_helper";
139   std::string expected_output =
140       "ctor: argc=1 argv[0]=" + helper + "\n" +
141       "main: argc=1 argv[0]=" + helper + "\n" +
142       "__progname=exec_linker_helper\n" +
143       "helper_func called\n";
144   ExecTestHelper eth;
145   eth.SetArgs({ path_to_linker, helper.c_str(), nullptr });
146   eth.Run([&]() { execve(path_to_linker, eth.GetArgs(), eth.GetEnv()); }, 0, nullptr);
147   ASSERT_EQ(expected_output, eth.GetOutput());
148 #endif
149 }
150 
TEST(dl,exec_linker_load_self)151 TEST(dl, exec_linker_load_self) {
152 #if defined(__BIONIC__)
153   const char* path_to_linker = PathToLinker();
154   std::string error_message = "error: linker cannot load itself\n";
155   ExecTestHelper eth;
156   eth.SetArgs({ path_to_linker, path_to_linker, nullptr });
157   eth.Run([&]() { execve(path_to_linker, eth.GetArgs(), eth.GetEnv()); }, EXIT_FAILURE, error_message.c_str());
158 #endif
159 }
160 
TEST(dl,preinit_system_calls)161 TEST(dl, preinit_system_calls) {
162 #if defined(__BIONIC__)
163   SKIP_WITH_HWASAN << "hwasan not initialized in preinit_array, b/124007027";
164   std::string helper = GetTestLibRoot() + "/preinit_syscall_test_helper";
165   ExecTestHelper eth;
166   eth.SetArgs({ helper.c_str(), nullptr });
167   eth.Run([&]() { execve(helper.c_str(), eth.GetArgs(), eth.GetEnv()); }, 0, nullptr);
168 #endif
169 }
170 
TEST(dl,preinit_getauxval)171 TEST(dl, preinit_getauxval) {
172 #if defined(__BIONIC__)
173   SKIP_WITH_HWASAN << "hwasan not initialized in preinit_array, b/124007027";
174   std::string helper = GetTestLibRoot() + "/preinit_getauxval_test_helper";
175   ExecTestHelper eth;
176   eth.SetArgs({ helper.c_str(), nullptr });
177   eth.Run([&]() { execve(helper.c_str(), eth.GetArgs(), eth.GetEnv()); }, 0, nullptr);
178 #else
179   // Force a failure when not compiled for bionic so the test is considered a pass.
180   ASSERT_TRUE(false);
181 #endif
182 }
183 
184 
TEST(dl,exec_without_ld_preload)185 TEST(dl, exec_without_ld_preload) {
186 #if defined(__BIONIC__)
187   std::string helper = GetTestLibRoot() + "/ld_preload_test_helper";
188   ExecTestHelper eth;
189   eth.SetArgs({ helper.c_str(), nullptr });
190   eth.Run([&]() { execve(helper.c_str(), eth.GetArgs(), eth.GetEnv()); }, 0, "12345");
191 #endif
192 }
193 
TEST(dl,exec_with_ld_preload)194 TEST(dl, exec_with_ld_preload) {
195 #if defined(__BIONIC__)
196   std::string helper = GetTestLibRoot() + "/ld_preload_test_helper";
197   std::string env = std::string("LD_PRELOAD=") + GetTestLibRoot() + "/ld_preload_test_helper_lib2.so";
198   ExecTestHelper eth;
199   eth.SetArgs({ helper.c_str(), nullptr });
200   eth.SetEnv({ env.c_str(), nullptr });
201   // ld_preload_test_helper calls get_value_from_lib() and returns the value.
202   // The symbol is defined by two libs: ld_preload_test_helper_lib.so and
203   // ld_preloaded_lib.so. The former is DT_NEEDED and the latter is LD_PRELOADED
204   // via this execution. The main executable is linked to the LD_PRELOADED lib
205   // and the value given from the lib is returned.
206   eth.Run([&]() { execve(helper.c_str(), eth.GetArgs(), eth.GetEnv()); }, 0, "54321");
207 #endif
208 }
209 
210 
211 // ld_config_test_helper must fail because it is depending on a lib which is not
212 // in the search path
213 //
214 // Call sequence is...
215 // _helper -- (get_value_from_lib()) -->
216 //     _lib1.so -- (get_value_from_another_lib()) -->
217 //       _lib2.so (returns 12345)
218 // The two libs are in ns2/ subdir.
TEST(dl,exec_without_ld_config_file)219 TEST(dl, exec_without_ld_config_file) {
220 #if defined(__BIONIC__)
221   std::string error_message = "CANNOT LINK EXECUTABLE \"" + GetTestLibRoot() +
222                               "/ld_config_test_helper\": library \"ld_config_test_helper_lib1.so\" "
223                               "not found: needed by main executable\n";
224   std::string helper = GetTestLibRoot() + "/ld_config_test_helper";
225   ExecTestHelper eth;
226   eth.SetArgs({ helper.c_str(), nullptr });
227   eth.Run([&]() { execve(helper.c_str(), eth.GetArgs(), eth.GetEnv()); }, EXIT_FAILURE, error_message.c_str());
228 #endif
229 }
230 
231 #if defined(__BIONIC__)
232 extern "C" void android_get_LD_LIBRARY_PATH(char*, size_t);
create_ld_config_file(const char * config_file)233 static void create_ld_config_file(const char* config_file) {
234   char default_search_paths[PATH_MAX];
235   android_get_LD_LIBRARY_PATH(default_search_paths, sizeof(default_search_paths));
236 
237   std::ofstream fout(config_file, std::ios::out);
238   fout << "dir.test = " << GetTestLibRoot() << "/" << std::endl
239        << "[test]" << std::endl
240        << "additional.namespaces = ns2" << std::endl
241        << "namespace.default.search.paths = " << GetTestLibRoot() << std::endl
242        << "namespace.default.links = ns2" << std::endl
243        << "namespace.default.link.ns2.shared_libs = "
244           "libc.so:libm.so:libdl.so:ld_config_test_helper_lib1.so"
245        << std::endl
246        << "namespace.ns2.search.paths = " << default_search_paths << ":" << GetTestLibRoot()
247        << "/ns2" << std::endl;
248   fout.close();
249 }
250 #endif
251 
252 #if defined(__BIONIC__)
253 // This test can't rely on ro.debuggable, because it might have been forced on
254 // in a user build ("Force Debuggable"). In that configuration, ro.debuggable is
255 // true, but Bionic's LD_CONFIG_FILE testing support is still disabled.
is_user_build()256 static bool is_user_build() {
257   return android::base::GetProperty("ro.build.type", "user") == std::string("user");
258 }
259 #endif
260 
261 // lib1.so and lib2.so are now searchable by having another namespace 'ns2'
262 // whose search paths include the 'ns2/' subdir.
263 //
264 // lib1.so is linked with DF_1_GLOBAL, so both it and the executable are added
265 // to every namespace.
266 //
267 // namespace configuration ('*' indicates primary ns)
268 //  - default: exe[*], lib1.so
269 //  - ns2: exe, lib1.so[*], lib2.so[*]
270 //
TEST(dl,exec_with_ld_config_file)271 TEST(dl, exec_with_ld_config_file) {
272 #if defined(__BIONIC__)
273   SKIP_WITH_HWASAN << "libclang_rt.hwasan is not found with custom ld config";
274   if (is_user_build()) {
275     GTEST_SKIP() << "LD_CONFIG_FILE is not supported on user build";
276   }
277   std::string helper = GetTestLibRoot() + "/ld_config_test_helper";
278   TemporaryFile config_file;
279   create_ld_config_file(config_file.path);
280   std::string env = std::string("LD_CONFIG_FILE=") + config_file.path;
281   ExecTestHelper eth;
282   eth.SetArgs({ helper.c_str(), nullptr });
283   eth.SetEnv({ env.c_str(), nullptr });
284   eth.Run([&]() { execve(helper.c_str(), eth.GetArgs(), eth.GetEnv()); }, 0,
285           "foo lib1\n"
286           "lib1_call_funcs\n"
287           "foo lib1\n"
288           "bar lib2\n");
289 #endif
290 }
291 
292 // lib3.so has same foo and bar symbols as lib2.so. lib3.so is LD_PRELOADed.
293 // This test ensures that LD_PRELOADed libs are available to all namespaces.
294 //
295 // namespace configuration ('*' indicates primary ns)
296 //  - default: exe[*], lib3.so[*], lib1.so
297 //  - ns2: exe, lib3.so, lib1.so[*], lib2.so[*]
298 //
299 // Ensure that, in both namespaces, a call to foo calls the lib3.so symbol,
300 // which then calls the lib1.so symbol using RTLD_NEXT. Ensure that RTLD_NEXT
301 // finds nothing when called from lib1.so.
302 //
303 // For the bar symbol, lib3.so's primary namespace is the default namespace, but
304 // lib2.so is not in the default namespace, so using RTLD_NEXT from lib3.so
305 // doesn't find the symbol in lib2.so.
TEST(dl,exec_with_ld_config_file_with_ld_preload)306 TEST(dl, exec_with_ld_config_file_with_ld_preload) {
307 #if defined(__BIONIC__)
308   SKIP_WITH_HWASAN << "libclang_rt.hwasan is not found with custom ld config";
309   if (is_user_build()) {
310     GTEST_SKIP() << "LD_CONFIG_FILE is not supported on user build";
311   }
312   std::string helper = GetTestLibRoot() + "/ld_config_test_helper";
313   TemporaryFile config_file;
314   create_ld_config_file(config_file.path);
315   std::string env = std::string("LD_CONFIG_FILE=") + config_file.path;
316   std::string env2 = std::string("LD_PRELOAD=") + GetTestLibRoot() + "/ld_config_test_helper_lib3.so";
317   ExecTestHelper eth;
318   eth.SetArgs({ helper.c_str(), nullptr });
319   eth.SetEnv({ env.c_str(), env2.c_str(), nullptr });
320   eth.Run([&]() { execve(helper.c_str(), eth.GetArgs(), eth.GetEnv()); }, 0,
321           "foo lib3\n"
322           "foo lib1\n"
323           "lib1_call_funcs\n"
324           "foo lib3\n"
325           "foo lib1\n"
326           "bar lib3\n"
327           "lib3_call_funcs\n"
328           "foo lib3\n"
329           "foo lib1\n"
330           "bar lib3\n");
331 #endif
332 }
333 
334 // ensures that LD_CONFIG_FILE env var does not work for production builds.
335 // The test input is the same as exec_with_ld_config_file, but it must fail in
336 // this case.
TEST(dl,disable_ld_config_file)337 TEST(dl, disable_ld_config_file) {
338 #if defined(__BIONIC__)
339   if (getuid() == 0) {
340     // when executed from the shell (e.g. not as part of CTS), skip the test.
341     // This test is only for CTS.
342     GTEST_SKIP() << "test is not supported with root uid";
343   }
344   if (!is_user_build()) {
345     GTEST_SKIP() << "test requires user build";
346   }
347 
348   std::string error_message =
349       std::string("CANNOT LINK EXECUTABLE ") + "\"" + GetTestLibRoot() +
350       "/ld_config_test_helper\": " +
351       "library \"ld_config_test_helper_lib1.so\" not found: needed by main executable\n";
352   std::string helper = GetTestLibRoot() + "/ld_config_test_helper";
353   TemporaryFile config_file;
354   create_ld_config_file(config_file.path);
355   std::string env = std::string("LD_CONFIG_FILE=") + config_file.path;
356   ExecTestHelper eth;
357   eth.SetArgs({ helper.c_str(), nullptr });
358   eth.SetEnv({ env.c_str(), nullptr });
359   eth.Run([&]() { execve(helper.c_str(), eth.GetArgs(), eth.GetEnv()); }, EXIT_FAILURE, error_message.c_str());
360 #endif
361 }
362 
RelocationsTest(const char * lib,const char * expectation)363 static void RelocationsTest(const char* lib, const char* expectation) {
364 #if defined(__BIONIC__)
365   // Does readelf think the .so file looks right?
366   const std::string path = GetTestLibRoot() + "/" + lib;
367   ExecTestHelper eth;
368   eth.SetArgs({ "readelf", "-SW", path.c_str(), nullptr });
369   eth.Run([&]() { execvpe("readelf", eth.GetArgs(), eth.GetEnv()); }, 0, nullptr);
370 
371   ASSERT_TRUE(std::regex_search(eth.GetOutput(), std::regex(expectation))) << eth.GetOutput();
372 
373   // Can we load it?
374   void* handle = dlopen(lib, RTLD_NOW);
375   ASSERT_TRUE(handle != nullptr) << dlerror();
376 #else
377   UNUSED(lib);
378   UNUSED(expectation);
379   GTEST_SKIP() << "test is not supported on glibc";
380 #endif
381 }
382 
TEST(dl,relocations_RELR)383 TEST(dl, relocations_RELR) {
384   RelocationsTest("librelocations-RELR.so", "\\.relr\\.dyn * RELR");
385 }
386 
TEST(dl,relocations_ANDROID_RELR)387 TEST(dl, relocations_ANDROID_RELR) {
388   RelocationsTest("librelocations-ANDROID_RELR.so", "\\.relr\\.dyn * ANDROID_RELR");
389 }
390 
TEST(dl,relocations_ANDROID_REL)391 TEST(dl, relocations_ANDROID_REL) {
392   RelocationsTest("librelocations-ANDROID_REL.so",
393 #if __LP64__
394                   "\\.rela\\.dyn * ANDROID_RELA"
395 #else
396                   "\\.rel\\.dyn * ANDROID_REL"
397 #endif
398   );
399 }
400 
TEST(dl,relocations_fat)401 TEST(dl, relocations_fat) {
402   RelocationsTest("librelocations-fat.so",
403 #if __LP64__
404                   "\\.rela\\.dyn * RELA"
405 #else
406                   "\\.rel\\.dyn * REL"
407 #endif
408   );
409 }
410