• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 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 <elf.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <inttypes.h>
24 #include <link.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <unistd.h>
28 
29 #include <android/dlext.h>
30 #include <android-base/file.h>
31 #include <android-base/strings.h>
32 #include <android-base/test_utils.h>
33 
34 #include <sys/mman.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <sys/vfs.h>
38 #include <sys/wait.h>
39 
40 #include <meminfo/procmeminfo.h>
41 #include <procinfo/process_map.h>
42 #include <ziparchive/zip_archive.h>
43 
44 #include "bionic/mte.h"
45 #include "bionic/page.h"
46 #include "core_shared_libs.h"
47 #include "dlext_private_tests.h"
48 #include "dlfcn_symlink_support.h"
49 #include "gtest_globals.h"
50 #include "utils.h"
51 
52 #define ASSERT_DL_NOTNULL(ptr) \
53     ASSERT_TRUE((ptr) != nullptr) << "dlerror: " << dlerror()
54 
55 #define ASSERT_DL_ZERO(i) \
56     ASSERT_EQ(0, i) << "dlerror: " << dlerror()
57 
58 #define ASSERT_NOERROR(i) \
59     ASSERT_NE(-1, i) << "errno: " << strerror(errno)
60 
61 #define ASSERT_SUBSTR(needle, haystack) \
62     ASSERT_PRED_FORMAT2(::testing::IsSubstring, needle, haystack)
63 
64 
65 typedef int (*fn)(void);
66 constexpr const char* kLibName = "libdlext_test.so";
67 constexpr const char* kLibNameRecursive = "libdlext_test_recursive.so";
68 constexpr const char* kLibNameNoRelro = "libdlext_test_norelro.so";
69 constexpr const char* kLibZipSimpleZip = "libdir/libatest_simple_zip.so";
70 constexpr auto kLibSize = 1024 * 1024; // how much address space to reserve for it
71 
72 class DlExtTest : public ::testing::Test {
73 protected:
SetUp()74   void SetUp() override {
75     handle_ = nullptr;
76     // verify that we don't have the library loaded already
77     void* h = dlopen(kLibName, RTLD_NOW | RTLD_NOLOAD);
78     ASSERT_TRUE(h == nullptr);
79     h = dlopen(kLibNameNoRelro, RTLD_NOW | RTLD_NOLOAD);
80     ASSERT_TRUE(h == nullptr);
81     // call dlerror() to swallow the error, and check it was the one we wanted
82     ASSERT_EQ(std::string("dlopen failed: library \"") + kLibNameNoRelro + "\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
83   }
84 
TearDown()85   void TearDown() override {
86     if (handle_ != nullptr) {
87       ASSERT_DL_ZERO(dlclose(handle_));
88     }
89   }
90 
91   void* handle_;
92   const size_t kPageSize = getpagesize();
93 };
94 
TEST_F(DlExtTest,ExtInfoNull)95 TEST_F(DlExtTest, ExtInfoNull) {
96   handle_ = android_dlopen_ext(kLibName, RTLD_NOW, nullptr);
97   ASSERT_DL_NOTNULL(handle_);
98   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
99   ASSERT_DL_NOTNULL(f);
100   EXPECT_EQ(4, f());
101 }
102 
TEST_F(DlExtTest,ExtInfoNoFlags)103 TEST_F(DlExtTest, ExtInfoNoFlags) {
104   android_dlextinfo extinfo;
105   extinfo.flags = 0;
106   handle_ = android_dlopen_ext(kLibName, RTLD_NOW, &extinfo);
107   ASSERT_DL_NOTNULL(handle_);
108   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
109   ASSERT_DL_NOTNULL(f);
110   EXPECT_EQ(4, f());
111 }
112 
TEST_F(DlExtTest,ExtInfoUseFd)113 TEST_F(DlExtTest, ExtInfoUseFd) {
114   const std::string lib_path = GetTestLibRoot() + "/libdlext_test_fd/libdlext_test_fd.so";
115 
116   android_dlextinfo extinfo;
117   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD;
118   extinfo.library_fd = TEMP_FAILURE_RETRY(open(lib_path.c_str(), O_RDONLY | O_CLOEXEC));
119   ASSERT_TRUE(extinfo.library_fd != -1);
120   handle_ = android_dlopen_ext(lib_path.c_str(), RTLD_NOW, &extinfo);
121   ASSERT_DL_NOTNULL(handle_);
122   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
123   ASSERT_DL_NOTNULL(f);
124   EXPECT_EQ(4, f());
125 
126   uint32_t* taxicab_number = reinterpret_cast<uint32_t*>(dlsym(handle_, "dlopen_testlib_taxicab_number"));
127   ASSERT_DL_NOTNULL(taxicab_number);
128   EXPECT_EQ(1729U, *taxicab_number);
129 }
130 
TEST_F(DlExtTest,ExtInfoUseFdWithOffset)131 TEST_F(DlExtTest, ExtInfoUseFdWithOffset) {
132   const std::string lib_path = GetTestLibRoot() + "/libdlext_test_zip/libdlext_test_zip_zipaligned.zip";
133 
134   android_dlextinfo extinfo;
135   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD | ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET;
136   extinfo.library_fd = TEMP_FAILURE_RETRY(open(lib_path.c_str(), O_RDONLY | O_CLOEXEC));
137 
138   // Find the offset of the shared library in the zip.
139   ZipArchiveHandle handle;
140   ASSERT_EQ(0, OpenArchive(lib_path.c_str(), &handle));
141   ZipEntry zip_entry;
142   ASSERT_EQ(0, FindEntry(handle, kLibZipSimpleZip, &zip_entry));
143   extinfo.library_fd_offset = zip_entry.offset;
144   CloseArchive(handle);
145 
146   handle_ = android_dlopen_ext(lib_path.c_str(), RTLD_NOW, &extinfo);
147   ASSERT_DL_NOTNULL(handle_);
148 
149   uint32_t* taxicab_number = reinterpret_cast<uint32_t*>(dlsym(handle_, "dlopen_testlib_taxicab_number"));
150   ASSERT_DL_NOTNULL(taxicab_number);
151   EXPECT_EQ(1729U, *taxicab_number);
152 }
153 
TEST_F(DlExtTest,ExtInfoUseFdWithInvalidOffset)154 TEST_F(DlExtTest, ExtInfoUseFdWithInvalidOffset) {
155   const std::string lib_path = GetTestLibRoot() + "/libdlext_test_zip/libdlext_test_zip_zipaligned.zip";
156 
157   android_dlextinfo extinfo;
158   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD | ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET;
159   extinfo.library_fd = TEMP_FAILURE_RETRY(open(lib_path.c_str(), O_RDONLY | O_CLOEXEC));
160   extinfo.library_fd_offset = 17;
161 
162   handle_ = android_dlopen_ext("libname_placeholder", RTLD_NOW, &extinfo);
163   ASSERT_TRUE(handle_ == nullptr);
164   ASSERT_STREQ("dlopen failed: file offset for the library \"libname_placeholder\" is not page-aligned: 17", dlerror());
165 
166   // Test an address above 2^44, for http://b/18178121 .
167   extinfo.library_fd_offset = (5LL << 48) + kPageSize;
168   handle_ = android_dlopen_ext("libname_placeholder", RTLD_NOW, &extinfo);
169   ASSERT_TRUE(handle_ == nullptr);
170   ASSERT_SUBSTR("dlopen failed: file offset for the library \"libname_placeholder\" >= file size", dlerror());
171 
172   extinfo.library_fd_offset = 0LL - kPageSize;
173   handle_ = android_dlopen_ext("libname_placeholder", RTLD_NOW, &extinfo);
174   ASSERT_TRUE(handle_ == nullptr);
175   ASSERT_SUBSTR("dlopen failed: file offset for the library \"libname_placeholder\" is negative", dlerror());
176 
177   extinfo.library_fd_offset = 0;
178   handle_ = android_dlopen_ext("libname_ignored", RTLD_NOW, &extinfo);
179   ASSERT_TRUE(handle_ == nullptr);
180   ASSERT_EQ("dlopen failed: \"" + lib_path + "\" has bad ELF magic: 504b0304", dlerror());
181 
182   // Check if dlsym works after unsuccessful dlopen().
183   // Supply non-exiting one to make linker visit every soinfo.
184   void* sym = dlsym(RTLD_DEFAULT, "this_symbol_does_not_exist___");
185   ASSERT_TRUE(sym == nullptr);
186 
187   close(extinfo.library_fd);
188 }
189 
TEST_F(DlExtTest,ExtInfoUseOffsetWithoutFd)190 TEST_F(DlExtTest, ExtInfoUseOffsetWithoutFd) {
191   android_dlextinfo extinfo;
192   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET;
193   // This offset will not be used, so it doesn't matter.
194   extinfo.library_fd_offset = 0;
195 
196   handle_ = android_dlopen_ext("/some/lib/that/does_not_exist", RTLD_NOW, &extinfo);
197   ASSERT_TRUE(handle_ == nullptr);
198   ASSERT_STREQ("dlopen failed: invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without ANDROID_DLEXT_USE_LIBRARY_FD): 0x20", dlerror());
199 }
200 
TEST(dlext,android_dlopen_ext_force_load_smoke)201 TEST(dlext, android_dlopen_ext_force_load_smoke) {
202   DlfcnSymlink symlink("android_dlopen_ext_force_load_smoke");
203   const std::string symlink_name = basename(symlink.get_symlink_path().c_str());
204   // 1. Open actual file
205   void* handle = dlopen("libdlext_test.so", RTLD_NOW);
206   ASSERT_DL_NOTNULL(handle);
207   // 2. Open link with force_load flag set
208   android_dlextinfo extinfo;
209   extinfo.flags = ANDROID_DLEXT_FORCE_LOAD;
210   void* handle2 = android_dlopen_ext(symlink_name.c_str(), RTLD_NOW, &extinfo);
211   ASSERT_DL_NOTNULL(handle2);
212   ASSERT_TRUE(handle != handle2);
213 
214   dlclose(handle2);
215   dlclose(handle);
216 }
217 
TEST(dlext,android_dlopen_ext_force_load_soname_exception)218 TEST(dlext, android_dlopen_ext_force_load_soname_exception) {
219   DlfcnSymlink symlink("android_dlopen_ext_force_load_soname_exception");
220   const std::string symlink_name = basename(symlink.get_symlink_path().c_str());
221   // Check if soname lookup still returns already loaded library
222   // when ANDROID_DLEXT_FORCE_LOAD flag is specified.
223   void* handle = dlopen(symlink_name.c_str(), RTLD_NOW);
224   ASSERT_DL_NOTNULL(handle);
225 
226   android_dlextinfo extinfo;
227   extinfo.flags = ANDROID_DLEXT_FORCE_LOAD;
228 
229   // Note that 'libdlext_test.so' is dt_soname for the symlink_name
230   void* handle2 = android_dlopen_ext("libdlext_test.so", RTLD_NOW, &extinfo);
231 
232   ASSERT_DL_NOTNULL(handle2);
233   ASSERT_TRUE(handle == handle2);
234 
235   dlclose(handle2);
236   dlclose(handle);
237 }
238 
TEST(dlfcn,dlopen_from_nullptr_android_api_level_28)239 TEST(dlfcn, dlopen_from_nullptr_android_api_level_28) {
240   // Regression test for http://b/123972211. Testing dlopen(nullptr) when target sdk is P
241   android_set_application_target_sdk_version(28);
242   ASSERT_TRUE(dlopen(nullptr, RTLD_NOW) != nullptr);
243 }
244 
245 // Test system path translation for backward compatibility. http://b/130219528
TEST(dlfcn,dlopen_system_libicuuc_android_api_level_28)246 TEST(dlfcn, dlopen_system_libicuuc_android_api_level_28) {
247   android_set_application_target_sdk_version(28);
248   ASSERT_TRUE(dlopen(PATH_TO_SYSTEM_LIB "libicuuc.so", RTLD_NOW) != nullptr);
249   ASSERT_TRUE(dlopen(PATH_TO_SYSTEM_LIB "libicui18n.so", RTLD_NOW) != nullptr);
250 }
251 
TEST(dlfcn,dlopen_system_libicuuc_android_api_level_29)252 TEST(dlfcn, dlopen_system_libicuuc_android_api_level_29) {
253   android_set_application_target_sdk_version(29);
254   ASSERT_TRUE(dlopen(PATH_TO_SYSTEM_LIB "libicuuc.so", RTLD_NOW) == nullptr);
255   ASSERT_TRUE(dlopen(PATH_TO_SYSTEM_LIB "libicui18n.so", RTLD_NOW) == nullptr);
256 }
257 
TEST(dlfcn,dlopen_system_libicuuc_android_api_level_current)258 TEST(dlfcn, dlopen_system_libicuuc_android_api_level_current) {
259   ASSERT_TRUE(dlopen(PATH_TO_SYSTEM_LIB "libicuuc.so", RTLD_NOW) == nullptr);
260   ASSERT_TRUE(dlopen(PATH_TO_SYSTEM_LIB "libicui18n.so", RTLD_NOW) == nullptr);
261 }
262 
TEST(dlfcn,dlopen_from_zip_absolute_path)263 TEST(dlfcn, dlopen_from_zip_absolute_path) {
264   const std::string lib_zip_path = "/libdlext_test_zip/libdlext_test_zip_zipaligned.zip";
265   const std::string lib_path = GetTestLibRoot() + lib_zip_path;
266 
267   void* handle = dlopen((lib_path + "!/libdir/libatest_simple_zip.so").c_str(), RTLD_NOW);
268   ASSERT_TRUE(handle != nullptr) << dlerror();
269 
270   uint32_t* taxicab_number = reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_testlib_taxicab_number"));
271   ASSERT_DL_NOTNULL(taxicab_number);
272   EXPECT_EQ(1729U, *taxicab_number);
273 
274   dlclose(handle);
275 }
276 
TEST(dlfcn,dlopen_from_zip_with_dt_runpath)277 TEST(dlfcn, dlopen_from_zip_with_dt_runpath) {
278   const std::string lib_zip_path = "/libdlext_test_runpath_zip/libdlext_test_runpath_zip_zipaligned.zip";
279   const std::string lib_path = GetTestLibRoot() + lib_zip_path;
280 
281   void* handle = dlopen((lib_path + "!/libdir/libtest_dt_runpath_d_zip.so").c_str(), RTLD_NOW);
282 
283   ASSERT_TRUE(handle != nullptr) << dlerror();
284 
285   typedef void *(* dlopen_b_fn)();
286   dlopen_b_fn fn = (dlopen_b_fn)dlsym(handle, "dlopen_b");
287   ASSERT_TRUE(fn != nullptr) << dlerror();
288 
289   void *p = fn();
290   ASSERT_TRUE(p != nullptr) << dlerror();
291 
292   dlclose(p);
293   dlclose(handle);
294 }
295 
TEST(dlfcn,dlopen_from_zip_ld_library_path)296 TEST(dlfcn, dlopen_from_zip_ld_library_path) {
297   const std::string lib_zip_path = "/libdlext_test_zip/libdlext_test_zip_zipaligned.zip";
298   const std::string lib_path = GetTestLibRoot() + lib_zip_path + "!/libdir";
299 
300   typedef void (*fn_t)(const char*);
301   fn_t android_update_LD_LIBRARY_PATH =
302       reinterpret_cast<fn_t>(dlsym(RTLD_DEFAULT, "android_update_LD_LIBRARY_PATH"));
303 
304   ASSERT_TRUE(android_update_LD_LIBRARY_PATH != nullptr) << dlerror();
305 
306   void* handle = dlopen("libdlext_test_zip.so", RTLD_NOW);
307   ASSERT_TRUE(handle == nullptr);
308 
309   android_update_LD_LIBRARY_PATH(lib_path.c_str());
310 
311   handle = dlopen("libdlext_test_zip.so", RTLD_NOW);
312   ASSERT_TRUE(handle != nullptr) << dlerror();
313 
314   int (*fn)(void);
315   fn = reinterpret_cast<int (*)(void)>(dlsym(handle, "getRandomNumber"));
316   ASSERT_TRUE(fn != nullptr);
317   EXPECT_EQ(4, fn());
318 
319   uint32_t* taxicab_number =
320           reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_testlib_taxicab_number"));
321   ASSERT_DL_NOTNULL(taxicab_number);
322   EXPECT_EQ(1729U, *taxicab_number);
323 
324   dlclose(handle);
325 }
326 
327 
TEST_F(DlExtTest,Reserved)328 TEST_F(DlExtTest, Reserved) {
329   void* start = mmap(nullptr, kLibSize, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
330   ASSERT_TRUE(start != MAP_FAILED);
331   android_dlextinfo extinfo;
332   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS;
333   extinfo.reserved_addr = start;
334   extinfo.reserved_size = kLibSize;
335   handle_ = android_dlopen_ext(kLibName, RTLD_NOW, &extinfo);
336   ASSERT_DL_NOTNULL(handle_);
337   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
338   ASSERT_DL_NOTNULL(f);
339   EXPECT_GE(reinterpret_cast<void*>(f), start);
340   EXPECT_LT(reinterpret_cast<void*>(f),
341             reinterpret_cast<char*>(start) + kLibSize);
342   EXPECT_EQ(4, f());
343 
344   // Check that after dlclose reserved address space is unmapped (and can be reused)
345   dlclose(handle_);
346   handle_ = nullptr;
347 
348   void* new_start = mmap(start, kPageSize, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
349   ASSERT_NE(start, new_start) << "dlclose unmapped reserved space";
350 }
351 
TEST_F(DlExtTest,ReservedTooSmall)352 TEST_F(DlExtTest, ReservedTooSmall) {
353   void* start = mmap(nullptr, kPageSize, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
354   ASSERT_TRUE(start != MAP_FAILED);
355   android_dlextinfo extinfo;
356   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS;
357   extinfo.reserved_addr = start;
358   extinfo.reserved_size = kPageSize;
359   handle_ = android_dlopen_ext(kLibName, RTLD_NOW, &extinfo);
360   EXPECT_EQ(nullptr, handle_);
361 }
362 
TEST_F(DlExtTest,ReservedRecursive)363 TEST_F(DlExtTest, ReservedRecursive) {
364   void* start = mmap(nullptr, kLibSize, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
365   ASSERT_TRUE(start != MAP_FAILED);
366   android_dlextinfo extinfo;
367   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS | ANDROID_DLEXT_RESERVED_ADDRESS_RECURSIVE;
368   extinfo.reserved_addr = start;
369   extinfo.reserved_size = kLibSize;
370   handle_ = android_dlopen_ext(kLibNameRecursive, RTLD_NOW, &extinfo);
371   ASSERT_DL_NOTNULL(handle_);
372 
373   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
374   ASSERT_DL_NOTNULL(f);
375   EXPECT_GE(reinterpret_cast<void*>(f), start);
376   EXPECT_LT(reinterpret_cast<void*>(f),
377             reinterpret_cast<char*>(start) + kLibSize);
378   EXPECT_EQ(4, f());
379 
380   f = reinterpret_cast<fn>(dlsym(handle_, "getBiggerRandomNumber"));
381   ASSERT_DL_NOTNULL(f);
382   EXPECT_GE(reinterpret_cast<void*>(f), start);
383   EXPECT_LT(reinterpret_cast<void*>(f),
384             reinterpret_cast<char*>(start) + kLibSize);
385   EXPECT_EQ(8, f());
386 
387   uint32_t* taxicab_number = reinterpret_cast<uint32_t*>(dlsym(handle_, "dlopen_testlib_taxicab_number"));
388   ASSERT_DL_NOTNULL(taxicab_number);
389   // Untag the pointer so that it can be compared with start, which will be untagged.
390   void* addr = reinterpret_cast<void*>(untag_address(taxicab_number));
391   EXPECT_GE(addr, start);
392   EXPECT_LT(addr, reinterpret_cast<char*>(start) + kLibSize);
393   EXPECT_EQ(1729U, *taxicab_number);
394 }
395 
TEST_F(DlExtTest,ReservedRecursiveTooSmall)396 TEST_F(DlExtTest, ReservedRecursiveTooSmall) {
397   void* start = mmap(nullptr, kPageSize, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
398   ASSERT_TRUE(start != MAP_FAILED);
399   android_dlextinfo extinfo;
400   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS | ANDROID_DLEXT_RESERVED_ADDRESS_RECURSIVE;
401   extinfo.reserved_addr = start;
402   extinfo.reserved_size = kPageSize;
403   handle_ = android_dlopen_ext(kLibNameRecursive, RTLD_NOW, &extinfo);
404   EXPECT_EQ(nullptr, handle_);
405 }
406 
TEST_F(DlExtTest,ReservedHint)407 TEST_F(DlExtTest, ReservedHint) {
408   void* start = mmap(nullptr, kLibSize, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
409   ASSERT_TRUE(start != MAP_FAILED);
410   android_dlextinfo extinfo;
411   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS_HINT;
412   extinfo.reserved_addr = start;
413   extinfo.reserved_size = kLibSize;
414   handle_ = android_dlopen_ext(kLibName, RTLD_NOW, &extinfo);
415   ASSERT_DL_NOTNULL(handle_);
416   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
417   ASSERT_DL_NOTNULL(f);
418   EXPECT_GE(reinterpret_cast<void*>(f), start);
419   EXPECT_LT(reinterpret_cast<void*>(f),
420             reinterpret_cast<char*>(start) + kLibSize);
421   EXPECT_EQ(4, f());
422 }
423 
TEST_F(DlExtTest,ReservedHintTooSmall)424 TEST_F(DlExtTest, ReservedHintTooSmall) {
425   void* start = mmap(nullptr, kPageSize, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
426   ASSERT_TRUE(start != MAP_FAILED);
427   android_dlextinfo extinfo;
428   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS_HINT;
429   extinfo.reserved_addr = start;
430   extinfo.reserved_size = kPageSize;
431   handle_ = android_dlopen_ext(kLibName, RTLD_NOW, &extinfo);
432   ASSERT_DL_NOTNULL(handle_);
433   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
434   ASSERT_DL_NOTNULL(f);
435   EXPECT_TRUE(reinterpret_cast<void*>(f) < start ||
436               (reinterpret_cast<void*>(f) >= reinterpret_cast<char*>(start) + kPageSize));
437   EXPECT_EQ(4, f());
438 }
439 
440 class DlExtRelroSharingTest : public DlExtTest {
441 protected:
SetUp()442   void SetUp() override {
443     DlExtTest::SetUp();
444     void* start = mmap(nullptr, kLibSize, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
445     ASSERT_TRUE(start != MAP_FAILED);
446     extinfo_.flags = ANDROID_DLEXT_RESERVED_ADDRESS;
447     extinfo_.reserved_addr = start;
448     extinfo_.reserved_size = kLibSize;
449     extinfo_.relro_fd = -1;
450   }
451 
TearDown()452   void TearDown() override {
453     DlExtTest::TearDown();
454   }
455 
CreateRelroFile(const char * lib,const char * relro_file,bool recursive)456   void CreateRelroFile(const char* lib, const char* relro_file, bool recursive) {
457     int relro_fd = open(relro_file, O_RDWR | O_TRUNC | O_CLOEXEC);
458     ASSERT_NOERROR(relro_fd);
459 
460     if (recursive) {
461       extinfo_.flags |= ANDROID_DLEXT_RESERVED_ADDRESS_RECURSIVE;
462     }
463 
464     pid_t pid = fork();
465     if (pid == 0) {
466       // child process
467       extinfo_.flags |= ANDROID_DLEXT_WRITE_RELRO;
468       extinfo_.relro_fd = relro_fd;
469       void* handle = android_dlopen_ext(lib, RTLD_NOW, &extinfo_);
470       if (handle == nullptr) {
471         fprintf(stderr, "in child: %s\n", dlerror());
472         exit(1);
473       }
474       fn f = reinterpret_cast<fn>(dlsym(handle, "getRandomNumber"));
475       ASSERT_DL_NOTNULL(f);
476       EXPECT_EQ(4, f());
477 
478       if (recursive) {
479         fn f = reinterpret_cast<fn>(dlsym(handle, "getBiggerRandomNumber"));
480         ASSERT_DL_NOTNULL(f);
481         EXPECT_EQ(8, f());
482       }
483 
484       uint32_t* taxicab_number =
485               reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_testlib_taxicab_number"));
486       ASSERT_DL_NOTNULL(taxicab_number);
487       EXPECT_EQ(1729U, *taxicab_number);
488       exit(testing::Test::HasFailure());
489     }
490 
491     // continuing in parent
492     ASSERT_NOERROR(close(relro_fd));
493     ASSERT_NOERROR(pid);
494     AssertChildExited(pid, 0);
495 
496     // reopen file for reading so it can be used
497     relro_fd = open(relro_file, O_RDONLY | O_CLOEXEC);
498     ASSERT_NOERROR(relro_fd);
499     extinfo_.flags |= ANDROID_DLEXT_USE_RELRO;
500     extinfo_.relro_fd = relro_fd;
501   }
502 
TryUsingRelro(const char * lib,bool recursive)503   void TryUsingRelro(const char* lib, bool recursive) {
504     handle_ = android_dlopen_ext(lib, RTLD_NOW, &extinfo_);
505     ASSERT_DL_NOTNULL(handle_);
506     fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
507     ASSERT_DL_NOTNULL(f);
508     EXPECT_EQ(4, f());
509 
510     if (recursive) {
511       fn f = reinterpret_cast<fn>(dlsym(handle_, "getBiggerRandomNumber"));
512       ASSERT_DL_NOTNULL(f);
513       EXPECT_EQ(8, f());
514     }
515 
516     uint32_t* taxicab_number =
517             reinterpret_cast<uint32_t*>(dlsym(handle_, "dlopen_testlib_taxicab_number"));
518     ASSERT_DL_NOTNULL(taxicab_number);
519     EXPECT_EQ(1729U, *taxicab_number);
520   }
521 
522   void SpawnChildrenAndMeasurePss(const char* lib, const char* relro_file, bool share_relro,
523                                   size_t* pss_out);
524 
525   std::string FindMappingName(void* ptr);
526 
527   android_dlextinfo extinfo_;
528 };
529 
TEST_F(DlExtRelroSharingTest,ChildWritesGoodData)530 TEST_F(DlExtRelroSharingTest, ChildWritesGoodData) {
531   TemporaryFile tf; // Use tf to get an unique filename.
532   ASSERT_NOERROR(close(tf.fd));
533 
534   ASSERT_NO_FATAL_FAILURE(CreateRelroFile(kLibName, tf.path, false));
535   ASSERT_NO_FATAL_FAILURE(TryUsingRelro(kLibName, false));
536   void* relro_data = dlsym(handle_, "lots_of_relro");
537   ASSERT_DL_NOTNULL(relro_data);
538   EXPECT_EQ(tf.path, FindMappingName(relro_data));
539 
540   // Use destructor of tf to close and unlink the file.
541   tf.fd = extinfo_.relro_fd;
542 }
543 
TEST_F(DlExtRelroSharingTest,ChildWritesGoodDataRecursive)544 TEST_F(DlExtRelroSharingTest, ChildWritesGoodDataRecursive) {
545   TemporaryFile tf; // Use tf to get an unique filename.
546   ASSERT_NOERROR(close(tf.fd));
547 
548   ASSERT_NO_FATAL_FAILURE(CreateRelroFile(kLibNameRecursive, tf.path, true));
549   ASSERT_NO_FATAL_FAILURE(TryUsingRelro(kLibNameRecursive, true));
550   void* relro_data = dlsym(handle_, "lots_of_relro");
551   ASSERT_DL_NOTNULL(relro_data);
552   EXPECT_EQ(tf.path, FindMappingName(relro_data));
553   void* recursive_relro_data = dlsym(handle_, "lots_more_relro");
554   ASSERT_DL_NOTNULL(recursive_relro_data);
555   EXPECT_EQ(tf.path, FindMappingName(recursive_relro_data));
556 
557 
558   // Use destructor of tf to close and unlink the file.
559   tf.fd = extinfo_.relro_fd;
560 }
561 
TEST_F(DlExtRelroSharingTest,CheckRelroSizes)562 TEST_F(DlExtRelroSharingTest, CheckRelroSizes) {
563   TemporaryFile tf1, tf2;
564   ASSERT_NOERROR(close(tf1.fd));
565   ASSERT_NOERROR(close(tf2.fd));
566 
567   ASSERT_NO_FATAL_FAILURE(CreateRelroFile(kLibNameRecursive, tf1.path, false));
568   struct stat no_recursive;
569   ASSERT_NOERROR(fstat(extinfo_.relro_fd, &no_recursive));
570   tf1.fd = extinfo_.relro_fd;
571 
572   ASSERT_NO_FATAL_FAILURE(CreateRelroFile(kLibNameRecursive, tf2.path, true));
573   struct stat with_recursive;
574   ASSERT_NOERROR(fstat(extinfo_.relro_fd, &with_recursive));
575   tf2.fd = extinfo_.relro_fd;
576 
577   // RELRO file should end up bigger when we use the recursive flag, since it
578   // includes data for more than one library.
579   ASSERT_GT(with_recursive.st_size, no_recursive.st_size);
580 }
581 
TEST_F(DlExtRelroSharingTest,ChildWritesNoRelro)582 TEST_F(DlExtRelroSharingTest, ChildWritesNoRelro) {
583   TemporaryFile tf; // // Use tf to get an unique filename.
584   ASSERT_NOERROR(close(tf.fd));
585 
586   ASSERT_NO_FATAL_FAILURE(CreateRelroFile(kLibNameNoRelro, tf.path, false));
587   ASSERT_NO_FATAL_FAILURE(TryUsingRelro(kLibNameNoRelro, false));
588 
589   // Use destructor of tf to close and unlink the file.
590   tf.fd = extinfo_.relro_fd;
591 }
592 
TEST_F(DlExtRelroSharingTest,RelroFileEmpty)593 TEST_F(DlExtRelroSharingTest, RelroFileEmpty) {
594   ASSERT_NO_FATAL_FAILURE(TryUsingRelro(kLibName, false));
595 }
596 
TEST_F(DlExtRelroSharingTest,VerifyMemorySaving)597 TEST_F(DlExtRelroSharingTest, VerifyMemorySaving) {
598   if (geteuid() != 0) GTEST_SKIP() << "This test must be run as root";
599 
600   TemporaryFile tf; // Use tf to get an unique filename.
601   ASSERT_NOERROR(close(tf.fd));
602 
603   ASSERT_NO_FATAL_FAILURE(CreateRelroFile(kLibName, tf.path, false));
604 
605   int pipefd[2];
606   ASSERT_NOERROR(pipe(pipefd));
607 
608   size_t without_sharing, with_sharing;
609   ASSERT_NO_FATAL_FAILURE(SpawnChildrenAndMeasurePss(kLibName, tf.path, false, &without_sharing));
610   ASSERT_NO_FATAL_FAILURE(SpawnChildrenAndMeasurePss(kLibName, tf.path, true, &with_sharing));
611   ASSERT_LT(with_sharing, without_sharing);
612 
613   // We expect the sharing to save at least 50% of the library's total PSS.
614   // In practice it saves 80%+ for this library in the test.
615   size_t pss_saved = without_sharing - with_sharing;
616   size_t expected_min_saved = without_sharing / 2;
617 
618   EXPECT_LT(expected_min_saved, pss_saved);
619 
620   // Use destructor of tf to close and unlink the file.
621   tf.fd = extinfo_.relro_fd;
622 }
623 
GetPss(bool shared_relro,const char * lib,const char * relro_file,pid_t pid,size_t * total_pss)624 void GetPss(bool shared_relro, const char* lib, const char* relro_file, pid_t pid,
625             size_t* total_pss) {
626   android::meminfo::ProcMemInfo proc_mem(pid);
627   const std::vector<android::meminfo::Vma>& maps = proc_mem.MapsWithoutUsageStats();
628   ASSERT_GT(maps.size(), 0UL);
629 
630   // Calculate total PSS of the library.
631   *total_pss = 0;
632   bool saw_relro_file = false;
633   for (auto& vma : maps) {
634     if (android::base::EndsWith(vma.name, lib) || (vma.name == relro_file)) {
635       if (vma.name == relro_file) {
636           saw_relro_file = true;
637       }
638 
639       android::meminfo::Vma update_vma(vma);
640       ASSERT_TRUE(proc_mem.FillInVmaStats(update_vma));
641       *total_pss += update_vma.usage.pss;
642     }
643   }
644 
645   if (shared_relro) ASSERT_TRUE(saw_relro_file);
646 }
647 
SpawnChildrenAndMeasurePss(const char * lib,const char * relro_file,bool share_relro,size_t * pss_out)648 void DlExtRelroSharingTest::SpawnChildrenAndMeasurePss(const char* lib, const char* relro_file,
649                                                        bool share_relro, size_t* pss_out) {
650   const int CHILDREN = 20;
651 
652   // Create children
653   pid_t child_pids[CHILDREN];
654   int childpipe[CHILDREN];
655   for (int i=0; i<CHILDREN; ++i) {
656     char read_buf;
657     int child_done_pipe[2], parent_done_pipe[2];
658     ASSERT_NOERROR(pipe(child_done_pipe));
659     ASSERT_NOERROR(pipe(parent_done_pipe));
660 
661     pid_t child = fork();
662     if (child == 0) {
663       // close the 'wrong' ends of the pipes in the child
664       close(child_done_pipe[0]);
665       close(parent_done_pipe[1]);
666 
667       // open the library
668       void* handle;
669       if (share_relro) {
670         handle = android_dlopen_ext(lib, RTLD_NOW, &extinfo_);
671       } else {
672         handle = dlopen(lib, RTLD_NOW);
673       }
674       if (handle == nullptr) {
675         fprintf(stderr, "in child: %s\n", dlerror());
676         exit(1);
677       }
678 
679       // close write end of child_done_pipe to signal the parent that we're done.
680       close(child_done_pipe[1]);
681 
682       // wait for the parent to close parent_done_pipe, then exit
683       read(parent_done_pipe[0], &read_buf, 1);
684       exit(0);
685     }
686 
687     ASSERT_NOERROR(child);
688 
689     // close the 'wrong' ends of the pipes in the parent
690     close(child_done_pipe[1]);
691     close(parent_done_pipe[0]);
692 
693     // wait for the child to be done
694     read(child_done_pipe[0], &read_buf, 1);
695     close(child_done_pipe[0]);
696 
697     // save the child's pid and the parent_done_pipe
698     child_pids[i] = child;
699     childpipe[i] = parent_done_pipe[1];
700   }
701 
702   // Sum the PSS of tested library of all the children
703   size_t total_pss = 0;
704   for (int i=0; i<CHILDREN; ++i) {
705     size_t child_pss;
706     ASSERT_NO_FATAL_FAILURE(GetPss(share_relro, lib, relro_file, child_pids[i], &child_pss));
707     total_pss += child_pss;
708   }
709   *pss_out = total_pss;
710 
711   // Close pipes and wait for children to exit
712   for (int i=0; i<CHILDREN; ++i) {
713     ASSERT_NOERROR(close(childpipe[i]));
714   }
715   for (int i = 0; i < CHILDREN; ++i) {
716     AssertChildExited(child_pids[i], 0);
717   }
718 }
719 
FindMappingName(void * ptr)720 std::string DlExtRelroSharingTest::FindMappingName(void* ptr) {
721   uint64_t addr = reinterpret_cast<uint64_t>(untag_address(ptr));
722   std::string found_name = "<not found>";
723 
724   EXPECT_TRUE(android::procinfo::ReadMapFile("/proc/self/maps",
725                                              [&](const android::procinfo::MapInfo& mapinfo) {
726                                                if (addr >= mapinfo.start && addr < mapinfo.end) {
727                                                  found_name = mapinfo.name;
728                                                }
729                                              }));
730 
731   return found_name;
732 }
733 
734 // Testing namespaces
735 static const char* g_public_lib = "libnstest_public.so";
736 
737 // These are libs shared with default namespace
738 static const std::string g_core_shared_libs = kCoreSharedLibs;
739 
TEST(dlext,ns_smoke)740 TEST(dlext, ns_smoke) {
741   static const char* root_lib = "libnstest_root.so";
742   std::string shared_libs = g_core_shared_libs + ":" + g_public_lib;
743 
744   ASSERT_FALSE(android_init_anonymous_namespace("", nullptr));
745   ASSERT_STREQ("android_init_anonymous_namespace failed: error linking namespaces"
746                " \"(anonymous)\"->\"(default)\": the list of shared libraries is empty.",
747                dlerror());
748 
749   const std::string lib_public_path = GetTestLibRoot() + "/public_namespace_libs/" + g_public_lib;
750   void* handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW);
751   ASSERT_TRUE(handle_public != nullptr) << dlerror();
752 
753   ASSERT_TRUE(android_init_anonymous_namespace(shared_libs.c_str(), nullptr)) << dlerror();
754 
755   // Check that libraries added to public namespace are not NODELETE
756   dlclose(handle_public);
757   handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW | RTLD_NOLOAD);
758   ASSERT_TRUE(handle_public == nullptr);
759   ASSERT_EQ(std::string("dlopen failed: library \"") + lib_public_path +
760                "\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
761 
762   handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW);
763 
764   // create "public namespace", share limited set of public libraries with
765 
766   android_namespace_t* ns1 =
767           android_create_namespace("private",
768                                    nullptr,
769                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
770                                    ANDROID_NAMESPACE_TYPE_REGULAR,
771                                    nullptr,
772                                    nullptr);
773   ASSERT_TRUE(ns1 != nullptr) << dlerror();
774   ASSERT_TRUE(android_link_namespaces(ns1, nullptr, shared_libs.c_str())) << dlerror();
775 
776   android_namespace_t* ns2 =
777           android_create_namespace("private_isolated",
778                                    nullptr,
779                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
780                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
781                                    nullptr,
782                                    nullptr);
783   ASSERT_TRUE(ns2 != nullptr) << dlerror();
784   ASSERT_TRUE(android_link_namespaces(ns2, nullptr, shared_libs.c_str())) << dlerror();
785 
786   // This should not have affect search path for default namespace:
787   ASSERT_TRUE(dlopen(root_lib, RTLD_NOW) == nullptr);
788   void* handle = dlopen(g_public_lib, RTLD_NOW);
789   ASSERT_TRUE(handle != nullptr) << dlerror();
790   dlclose(handle);
791 
792   // dlopen for a public library using an absolute path should work
793   // 1. For isolated namespaces
794   android_dlextinfo extinfo;
795   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
796   extinfo.library_namespace = ns2;
797   handle = android_dlopen_ext(lib_public_path.c_str(), RTLD_NOW, &extinfo);
798   ASSERT_TRUE(handle != nullptr) << dlerror();
799   ASSERT_TRUE(handle == handle_public);
800 
801   dlclose(handle);
802 
803   // 1.1 even if it wasn't loaded before
804   dlclose(handle_public);
805 
806   handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW | RTLD_NOLOAD);
807   ASSERT_TRUE(handle_public == nullptr);
808   ASSERT_EQ(std::string("dlopen failed: library \"") + lib_public_path +
809                "\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
810 
811   handle = android_dlopen_ext(lib_public_path.c_str(), RTLD_NOW, &extinfo);
812   ASSERT_TRUE(handle != nullptr) << dlerror();
813 
814   handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW);
815   ASSERT_TRUE(handle == handle_public);
816 
817   dlclose(handle);
818 
819   // 2. And for regular namespaces (make sure it does not load second copy of the library)
820   extinfo.library_namespace = ns1;
821   handle = android_dlopen_ext(lib_public_path.c_str(), RTLD_NOW, &extinfo);
822   ASSERT_TRUE(handle != nullptr) << dlerror();
823   ASSERT_TRUE(handle == handle_public);
824 
825   dlclose(handle);
826 
827   // 2.1 Unless it was not loaded before - in which case it will load a duplicate.
828   // TODO(dimitry): This is broken. Maybe we need to deprecate non-isolated namespaces?
829   dlclose(handle_public);
830 
831   handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW | RTLD_NOLOAD);
832   ASSERT_TRUE(handle_public == nullptr);
833   ASSERT_EQ(std::string("dlopen failed: library \"") + lib_public_path +
834                "\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
835 
836   handle = android_dlopen_ext(lib_public_path.c_str(), RTLD_NOW, &extinfo);
837   ASSERT_TRUE(handle != nullptr) << dlerror();
838 
839   handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW);
840 
841   ASSERT_TRUE(handle != handle_public);
842 
843   dlclose(handle);
844 
845   extinfo.library_namespace = ns1;
846 
847   void* handle1 = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
848   ASSERT_TRUE(handle1 != nullptr) << dlerror();
849 
850   extinfo.library_namespace = ns2;
851   void* handle2 = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
852   ASSERT_TRUE(handle2 != nullptr) << dlerror();
853 
854   ASSERT_TRUE(handle1 != handle2);
855 
856   typedef const char* (*fn_t)();
857 
858   fn_t ns_get_local_string1 = reinterpret_cast<fn_t>(dlsym(handle1, "ns_get_local_string"));
859   ASSERT_TRUE(ns_get_local_string1 != nullptr) << dlerror();
860   fn_t ns_get_local_string2 = reinterpret_cast<fn_t>(dlsym(handle2, "ns_get_local_string"));
861   ASSERT_TRUE(ns_get_local_string2 != nullptr) << dlerror();
862 
863   EXPECT_STREQ("This string is local to root library", ns_get_local_string1());
864   EXPECT_STREQ("This string is local to root library", ns_get_local_string2());
865 
866   ASSERT_TRUE(ns_get_local_string1() != ns_get_local_string2());
867 
868   fn_t ns_get_private_extern_string1 =
869           reinterpret_cast<fn_t>(dlsym(handle1, "ns_get_private_extern_string"));
870   ASSERT_TRUE(ns_get_private_extern_string1 != nullptr) << dlerror();
871   fn_t ns_get_private_extern_string2 =
872           reinterpret_cast<fn_t>(dlsym(handle2, "ns_get_private_extern_string"));
873   ASSERT_TRUE(ns_get_private_extern_string2 != nullptr) << dlerror();
874 
875   EXPECT_STREQ("This string is from private namespace", ns_get_private_extern_string1());
876   EXPECT_STREQ("This string is from private namespace", ns_get_private_extern_string2());
877 
878   ASSERT_TRUE(ns_get_private_extern_string1() != ns_get_private_extern_string2());
879 
880   fn_t ns_get_public_extern_string1 =
881           reinterpret_cast<fn_t>(dlsym(handle1, "ns_get_public_extern_string"));
882   ASSERT_TRUE(ns_get_public_extern_string1 != nullptr) << dlerror();
883   fn_t ns_get_public_extern_string2 =
884           reinterpret_cast<fn_t>(dlsym(handle2, "ns_get_public_extern_string"));
885   ASSERT_TRUE(ns_get_public_extern_string2 != nullptr) << dlerror();
886 
887   EXPECT_STREQ("This string is from public namespace", ns_get_public_extern_string1());
888   ASSERT_TRUE(ns_get_public_extern_string1() == ns_get_public_extern_string2());
889 
890   // and now check that dlopen() does the right thing in terms of preserving namespace
891   fn_t ns_get_dlopened_string1 = reinterpret_cast<fn_t>(dlsym(handle1, "ns_get_dlopened_string"));
892   ASSERT_TRUE(ns_get_dlopened_string1 != nullptr) << dlerror();
893   fn_t ns_get_dlopened_string2 = reinterpret_cast<fn_t>(dlsym(handle2, "ns_get_dlopened_string"));
894   ASSERT_TRUE(ns_get_dlopened_string2 != nullptr) << dlerror();
895 
896   EXPECT_STREQ("This string is from private namespace (dlopened library)", ns_get_dlopened_string1());
897   EXPECT_STREQ("This string is from private namespace (dlopened library)", ns_get_dlopened_string2());
898 
899   ASSERT_TRUE(ns_get_dlopened_string1() != ns_get_dlopened_string2());
900 
901   // Check that symbols from non-shared libraries a shared library depends on are not visible
902   // from original namespace.
903 
904   fn_t ns_get_internal_extern_string =
905           reinterpret_cast<fn_t>(dlsym(handle1, "ns_get_internal_extern_string"));
906   ASSERT_TRUE(ns_get_internal_extern_string != nullptr) << dlerror();
907   ASSERT_TRUE(ns_get_internal_extern_string() == nullptr) <<
908       "ns_get_internal_extern_string() expected to return null but returns \"" <<
909       ns_get_internal_extern_string() << "\"";
910 
911   dlclose(handle1);
912 
913   // Check if handle2 is still alive (and well)
914   ASSERT_STREQ("This string is local to root library", ns_get_local_string2());
915   ASSERT_STREQ("This string is from private namespace", ns_get_private_extern_string2());
916   ASSERT_STREQ("This string is from public namespace", ns_get_public_extern_string2());
917   ASSERT_STREQ("This string is from private namespace (dlopened library)", ns_get_dlopened_string2());
918 
919   dlclose(handle2);
920 }
921 
TEST(dlext,dlopen_ext_use_o_tmpfile_fd)922 TEST(dlext, dlopen_ext_use_o_tmpfile_fd) {
923   const std::string lib_path = GetTestLibRoot() + "/libtest_simple.so";
924 
925   int tmpfd = TEMP_FAILURE_RETRY(
926         open(GetTestLibRoot().c_str(), O_TMPFILE | O_CLOEXEC | O_RDWR | O_EXCL, 0));
927 
928   // Ignore kernels without O_TMPFILE flag support
929   if (tmpfd == -1 && (errno == EISDIR || errno == EINVAL || errno == EOPNOTSUPP)) {
930     return;
931   }
932 
933   ASSERT_TRUE(tmpfd != -1) << strerror(errno);
934 
935   android_namespace_t* ns =
936           android_create_namespace("testing-o_tmpfile",
937                                    nullptr,
938                                    GetTestLibRoot().c_str(),
939                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
940                                    nullptr,
941                                    nullptr);
942 
943   ASSERT_DL_NOTNULL(ns);
944 
945   ASSERT_TRUE(android_link_namespaces(ns, nullptr, g_core_shared_libs.c_str())) << dlerror();
946 
947   std::string content;
948   ASSERT_TRUE(android::base::ReadFileToString(lib_path, &content)) << strerror(errno);
949   ASSERT_TRUE(android::base::WriteStringToFd(content, tmpfd)) << strerror(errno);
950 
951   android_dlextinfo extinfo;
952   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD | ANDROID_DLEXT_USE_NAMESPACE;
953   extinfo.library_fd = tmpfd;
954   extinfo.library_namespace = ns;
955 
956   void* handle = android_dlopen_ext("foobar", RTLD_NOW, &extinfo);
957 
958   ASSERT_DL_NOTNULL(handle);
959 
960   uint32_t* taxicab_number = reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_testlib_taxicab_number"));
961   ASSERT_DL_NOTNULL(taxicab_number);
962   EXPECT_EQ(1729U, *taxicab_number);
963   dlclose(handle);
964 }
965 
TEST(dlext,dlopen_ext_use_memfd)966 TEST(dlext, dlopen_ext_use_memfd) {
967   const std::string lib_path = GetTestLibRoot() + "/libtest_simple.so";
968 
969   // create memfd
970   int memfd = memfd_create("foobar", MFD_CLOEXEC);
971   ASSERT_TRUE(memfd != -1) << strerror(errno);
972 
973   // Check st.f_type is TMPFS_MAGIC for memfd
974   struct statfs st;
975   ASSERT_TRUE(TEMP_FAILURE_RETRY(fstatfs(memfd, &st)) == 0) << strerror(errno);
976   ASSERT_EQ(static_cast<decltype(st.f_type)>(TMPFS_MAGIC), st.f_type);
977 
978   android_namespace_t* ns =
979           android_create_namespace("testing-memfd",
980                                    nullptr,
981                                    GetTestLibRoot().c_str(),
982                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
983                                    nullptr,
984                                    nullptr);
985 
986   ASSERT_DL_NOTNULL(ns);
987 
988   ASSERT_TRUE(android_link_namespaces(ns, nullptr, g_core_shared_libs.c_str())) << dlerror();
989 
990   // read file into memfd backed one.
991   std::string content;
992   ASSERT_TRUE(android::base::ReadFileToString(lib_path, &content)) << strerror(errno);
993   ASSERT_TRUE(android::base::WriteStringToFd(content, memfd)) << strerror(errno);
994 
995   android_dlextinfo extinfo;
996   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD | ANDROID_DLEXT_USE_NAMESPACE;
997   extinfo.library_fd = memfd;
998   extinfo.library_namespace = ns;
999 
1000   void* handle = android_dlopen_ext("foobar", RTLD_NOW, &extinfo);
1001 
1002   ASSERT_DL_NOTNULL(handle);
1003 
1004   uint32_t* taxicab_number = reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_testlib_taxicab_number"));
1005   ASSERT_DL_NOTNULL(taxicab_number);
1006   EXPECT_EQ(1729U, *taxicab_number);
1007   dlclose(handle);
1008 }
1009 
TEST(dlext,ns_symbol_visibilty_one_namespace)1010 TEST(dlext, ns_symbol_visibilty_one_namespace) {
1011   static const char* root_lib = "libnstest_root.so";
1012   ASSERT_TRUE(android_init_anonymous_namespace(g_core_shared_libs.c_str(), nullptr));
1013 
1014   const std::string ns_search_path = GetTestLibRoot() + "/public_namespace_libs:" +
1015                                      GetTestLibRoot() + "/private_namespace_libs";
1016 
1017   android_namespace_t* ns =
1018           android_create_namespace("one",
1019                                    nullptr,
1020                                    ns_search_path.c_str(),
1021                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1022                                    nullptr,
1023                                    nullptr);
1024 
1025   ASSERT_TRUE(android_link_namespaces(ns, nullptr, g_core_shared_libs.c_str())) << dlerror();
1026 
1027   android_dlextinfo extinfo;
1028   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1029   extinfo.library_namespace = ns;
1030 
1031   void* handle = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
1032   ASSERT_TRUE(handle != nullptr) << dlerror();
1033 
1034   typedef const char* (*fn_t)();
1035 
1036   // Check that relocation worked correctly
1037   fn_t ns_get_internal_extern_string =
1038           reinterpret_cast<fn_t>(dlsym(handle, "ns_get_internal_extern_string"));
1039   ASSERT_TRUE(ns_get_internal_extern_string != nullptr) << dlerror();
1040   ASSERT_STREQ("This string is from a library a shared library depends on", ns_get_internal_extern_string());
1041 
1042   fn_t internal_extern_string_fn =
1043           reinterpret_cast<fn_t>(dlsym(handle, "internal_extern_string"));
1044   ASSERT_TRUE(internal_extern_string_fn != nullptr) << dlerror();
1045   ASSERT_STREQ("This string is from a library a shared library depends on", internal_extern_string_fn());
1046 }
1047 
TEST(dlext,ns_symbol_visibilty_between_namespaces)1048 TEST(dlext, ns_symbol_visibilty_between_namespaces) {
1049   static const char* root_lib = "libnstest_root.so";
1050   ASSERT_TRUE(android_init_anonymous_namespace(g_core_shared_libs.c_str(), nullptr));
1051 
1052   const std::string public_ns_search_path =  GetTestLibRoot() + "/public_namespace_libs";
1053   const std::string private_ns_search_path = GetTestLibRoot() + "/private_namespace_libs";
1054 
1055   android_namespace_t* ns_public =
1056           android_create_namespace("public",
1057                                    nullptr,
1058                                    public_ns_search_path.c_str(),
1059                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1060                                    nullptr,
1061                                    nullptr);
1062 
1063   ASSERT_TRUE(android_link_namespaces(ns_public, nullptr, g_core_shared_libs.c_str())) << dlerror();
1064 
1065   android_namespace_t* ns_private =
1066           android_create_namespace("private",
1067                                    nullptr,
1068                                    private_ns_search_path.c_str(),
1069                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1070                                    nullptr,
1071                                    nullptr);
1072 
1073   ASSERT_TRUE(android_link_namespaces(ns_private, ns_public, g_public_lib)) << dlerror();
1074   ASSERT_TRUE(android_link_namespaces(ns_private, nullptr, g_core_shared_libs.c_str())) << dlerror();
1075 
1076   android_dlextinfo extinfo;
1077   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1078   extinfo.library_namespace = ns_private;
1079 
1080   void* handle = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
1081   ASSERT_TRUE(handle != nullptr) << dlerror();
1082 
1083   typedef const char* (*fn_t)();
1084 
1085   // Check that relocation worked correctly
1086   fn_t ns_get_internal_extern_string =
1087           reinterpret_cast<fn_t>(dlsym(handle, "ns_get_internal_extern_string"));
1088   ASSERT_TRUE(ns_get_internal_extern_string != nullptr) << dlerror();
1089   ASSERT_TRUE(ns_get_internal_extern_string() == nullptr) <<
1090       "ns_get_internal_extern_string() expected to return null but returns \"" <<
1091       ns_get_internal_extern_string() << "\"";
1092 
1093   fn_t internal_extern_string_fn =
1094           reinterpret_cast<fn_t>(dlsym(handle, "internal_extern_string"));
1095   ASSERT_TRUE(internal_extern_string_fn == nullptr);
1096   ASSERT_STREQ("undefined symbol: internal_extern_string", dlerror());
1097 }
1098 
TEST(dlext,ns_unload_between_namespaces)1099 TEST(dlext, ns_unload_between_namespaces) {
1100   static const char* root_lib = "libnstest_root.so";
1101   ASSERT_TRUE(android_init_anonymous_namespace(g_core_shared_libs.c_str(), nullptr));
1102 
1103   const std::string public_ns_search_path =  GetTestLibRoot() + "/public_namespace_libs";
1104   const std::string private_ns_search_path = GetTestLibRoot() + "/private_namespace_libs";
1105 
1106   android_namespace_t* ns_public =
1107           android_create_namespace("public",
1108                                    nullptr,
1109                                    public_ns_search_path.c_str(),
1110                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1111                                    nullptr,
1112                                    nullptr);
1113 
1114   ASSERT_TRUE(android_link_namespaces(ns_public, nullptr, g_core_shared_libs.c_str())) << dlerror();
1115 
1116   android_namespace_t* ns_private =
1117           android_create_namespace("private",
1118                                    nullptr,
1119                                    private_ns_search_path.c_str(),
1120                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1121                                    nullptr,
1122                                    nullptr);
1123 
1124   ASSERT_TRUE(android_link_namespaces(ns_private, ns_public, g_public_lib)) << dlerror();
1125   ASSERT_TRUE(android_link_namespaces(ns_private, nullptr, g_core_shared_libs.c_str())) << dlerror();
1126 
1127   android_dlextinfo extinfo;
1128   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1129   extinfo.library_namespace = ns_private;
1130 
1131   void* handle = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
1132   ASSERT_TRUE(handle != nullptr) << dlerror();
1133 
1134   dlclose(handle);
1135   // Check that root_lib was unloaded
1136   handle = android_dlopen_ext(root_lib, RTLD_NOW | RTLD_NOLOAD, &extinfo);
1137   ASSERT_TRUE(handle == nullptr);
1138   ASSERT_EQ(std::string("dlopen failed: library \"") + root_lib +
1139             "\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
1140 
1141   // Check that shared library was unloaded in public ns
1142   extinfo.library_namespace = ns_public;
1143   handle = android_dlopen_ext(g_public_lib, RTLD_NOW | RTLD_NOLOAD, &extinfo);
1144   ASSERT_TRUE(handle == nullptr);
1145   ASSERT_EQ(std::string("dlopen failed: library \"") + g_public_lib +
1146             "\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
1147 }
1148 
TEST(dlext,ns_unload_between_namespaces_missing_symbol_direct)1149 TEST(dlext, ns_unload_between_namespaces_missing_symbol_direct) {
1150   ASSERT_TRUE(android_init_anonymous_namespace(g_core_shared_libs.c_str(), nullptr));
1151 
1152   const std::string public_ns_search_path =  GetTestLibRoot() + "/public_namespace_libs";
1153   const std::string private_ns_search_path = GetTestLibRoot() + "/private_namespace_libs";
1154 
1155   android_namespace_t* ns_public =
1156           android_create_namespace("public",
1157                                    nullptr,
1158                                    public_ns_search_path.c_str(),
1159                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1160                                    nullptr,
1161                                    nullptr);
1162 
1163   ASSERT_TRUE(android_link_namespaces(ns_public, nullptr, g_core_shared_libs.c_str())) << dlerror();
1164 
1165   android_namespace_t* ns_private =
1166           android_create_namespace("private",
1167                                    nullptr,
1168                                    private_ns_search_path.c_str(),
1169                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1170                                    nullptr,
1171                                    nullptr);
1172 
1173   ASSERT_TRUE(android_link_namespaces(ns_private, ns_public, "libtest_missing_symbol.so")) << dlerror();
1174   ASSERT_TRUE(android_link_namespaces(ns_private, nullptr, g_core_shared_libs.c_str())) << dlerror();
1175 
1176   android_dlextinfo extinfo;
1177   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1178   extinfo.library_namespace = ns_private;
1179 
1180   void* handle = android_dlopen_ext((public_ns_search_path + "/libtest_missing_symbol.so").c_str(),
1181                                     RTLD_NOW,
1182                                     &extinfo);
1183   ASSERT_TRUE(handle == nullptr);
1184   ASSERT_EQ(std::string("dlopen failed: cannot locate symbol \"dlopen_testlib_missing_symbol\" referenced by \"") +
1185             public_ns_search_path + "/libtest_missing_symbol.so\"...",
1186             dlerror());
1187 }
1188 
TEST(dlext,ns_unload_between_namespaces_missing_symbol_indirect)1189 TEST(dlext, ns_unload_between_namespaces_missing_symbol_indirect) {
1190   ASSERT_TRUE(android_init_anonymous_namespace(g_core_shared_libs.c_str(), nullptr));
1191 
1192   const std::string public_ns_search_path =  GetTestLibRoot() + "/public_namespace_libs";
1193   const std::string private_ns_search_path = GetTestLibRoot() + "/private_namespace_libs";
1194 
1195   android_namespace_t* ns_public =
1196           android_create_namespace("public",
1197                                    nullptr,
1198                                    public_ns_search_path.c_str(),
1199                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1200                                    nullptr,
1201                                    nullptr);
1202 
1203   ASSERT_TRUE(android_link_namespaces(ns_public, nullptr, g_core_shared_libs.c_str())) << dlerror();
1204 
1205   android_namespace_t* ns_private =
1206           android_create_namespace("private",
1207                                    nullptr,
1208                                    private_ns_search_path.c_str(),
1209                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1210                                    nullptr,
1211                                    nullptr);
1212 
1213   ASSERT_TRUE(android_link_namespaces(ns_private,
1214                                       ns_public,
1215                                       "libnstest_public.so:libtest_missing_symbol_child_public.so")
1216               ) << dlerror();
1217   ASSERT_TRUE(android_link_namespaces(ns_private, nullptr, g_core_shared_libs.c_str())) << dlerror();
1218 
1219   android_dlextinfo extinfo;
1220   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1221   extinfo.library_namespace = ns_private;
1222 
1223   void* handle = android_dlopen_ext("libtest_missing_symbol_root.so", RTLD_NOW, &extinfo);
1224   ASSERT_TRUE(handle == nullptr);
1225   ASSERT_EQ(std::string("dlopen failed: cannot locate symbol \"dlopen_testlib_missing_symbol\" referenced by \"") +
1226             private_ns_search_path + "/libtest_missing_symbol_root.so\"...",
1227             dlerror());
1228 }
1229 
TEST(dlext,ns_exempt_list_enabled)1230 TEST(dlext, ns_exempt_list_enabled) {
1231   ASSERT_TRUE(android_init_anonymous_namespace(g_core_shared_libs.c_str(), nullptr));
1232 
1233   const std::string ns_search_path = GetTestLibRoot() + "/private_namespace_libs";
1234 
1235   android_namespace_t* ns =
1236           android_create_namespace("namespace",
1237                                    nullptr,
1238                                    ns_search_path.c_str(),
1239                                    ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_EXEMPT_LIST_ENABLED,
1240                                    nullptr,
1241                                    nullptr);
1242 
1243   ASSERT_TRUE(android_link_namespaces(ns, nullptr, g_core_shared_libs.c_str())) << dlerror();
1244 
1245   android_dlextinfo extinfo;
1246   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1247   extinfo.library_namespace = ns;
1248 
1249   // An app targeting M can open libnativehelper.so because it's on the exempt-list.
1250   android_set_application_target_sdk_version(23);
1251   void* handle = android_dlopen_ext("libnativehelper.so", RTLD_NOW, &extinfo);
1252   ASSERT_TRUE(handle != nullptr) << dlerror();
1253 
1254   // Check that loader did not load another copy of libdl.so while loading exempted library.
1255   void* dlsym_ptr = dlsym(handle, "dlsym");
1256   ASSERT_TRUE(dlsym_ptr != nullptr) << dlerror();
1257   ASSERT_EQ(&dlsym, dlsym_ptr);
1258 
1259   dlclose(handle);
1260 
1261   // An app targeting N no longer has the exempt-list.
1262   android_set_application_target_sdk_version(24);
1263   handle = android_dlopen_ext("libnativehelper.so", RTLD_NOW, &extinfo);
1264   ASSERT_TRUE(handle == nullptr);
1265   ASSERT_STREQ("dlopen failed: library \"libnativehelper.so\" not found", dlerror());
1266 }
1267 
TEST(dlext,ns_exempt_list_disabled_by_default)1268 TEST(dlext, ns_exempt_list_disabled_by_default) {
1269   ASSERT_TRUE(android_init_anonymous_namespace(g_core_shared_libs.c_str(), nullptr));
1270 
1271   const std::string ns_search_path = GetTestLibRoot() + "/private_namespace_libs";
1272 
1273   android_namespace_t* ns =
1274           android_create_namespace("namespace",
1275                                    nullptr,
1276                                    ns_search_path.c_str(),
1277                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1278                                    nullptr,
1279                                    nullptr);
1280 
1281   ASSERT_TRUE(android_link_namespaces(ns, nullptr, g_core_shared_libs.c_str())) << dlerror();
1282 
1283   android_dlextinfo extinfo;
1284   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1285   extinfo.library_namespace = ns;
1286 
1287   android_set_application_target_sdk_version(23);
1288   void* handle = android_dlopen_ext("libnativehelper.so", RTLD_NOW, &extinfo);
1289   ASSERT_TRUE(handle == nullptr);
1290   ASSERT_STREQ("dlopen failed: library \"libnativehelper.so\" not found", dlerror());
1291 }
1292 
TEST(dlext,ns_cyclic_namespaces)1293 TEST(dlext, ns_cyclic_namespaces) {
1294   // Test that ns1->ns2->ns1 link does not break the loader
1295   ASSERT_TRUE(android_init_anonymous_namespace(g_core_shared_libs.c_str(), nullptr));
1296   std::string shared_libs = g_core_shared_libs + ":libthatdoesnotexist.so";
1297 
1298   const std::string ns_search_path =  GetTestLibRoot() + "/public_namespace_libs";
1299 
1300   android_namespace_t* ns1 =
1301           android_create_namespace("ns1",
1302                                    nullptr,
1303                                    ns_search_path.c_str(),
1304                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1305                                    nullptr,
1306                                    nullptr);
1307 
1308   ASSERT_TRUE(android_link_namespaces(ns1, nullptr, g_core_shared_libs.c_str())) << dlerror();
1309 
1310   android_namespace_t* ns2 =
1311           android_create_namespace("ns1",
1312                                    nullptr,
1313                                    ns_search_path.c_str(),
1314                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1315                                    nullptr,
1316                                    nullptr);
1317 
1318   ASSERT_TRUE(android_link_namespaces(ns2, nullptr, g_core_shared_libs.c_str())) << dlerror();
1319 
1320   ASSERT_TRUE(android_link_namespaces(ns2, ns1, shared_libs.c_str())) << dlerror();
1321   ASSERT_TRUE(android_link_namespaces(ns1, ns2, shared_libs.c_str())) << dlerror();
1322 
1323   android_dlextinfo extinfo;
1324   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1325   extinfo.library_namespace = ns1;
1326 
1327   void* handle = android_dlopen_ext("libthatdoesnotexist.so", RTLD_NOW, &extinfo);
1328   ASSERT_TRUE(handle == nullptr);
1329   ASSERT_STREQ("dlopen failed: library \"libthatdoesnotexist.so\" not found", dlerror());
1330 }
1331 
TEST(dlext,ns_isolated)1332 TEST(dlext, ns_isolated) {
1333   static const char* root_lib = "libnstest_root_not_isolated.so";
1334   std::string shared_libs = g_core_shared_libs + ":" + g_public_lib;
1335 
1336   const std::string lib_public_path = GetTestLibRoot() + "/public_namespace_libs/" + g_public_lib;
1337   void* handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW);
1338   ASSERT_TRUE(handle_public != nullptr) << dlerror();
1339 
1340   android_set_application_target_sdk_version(42U); // something > 23
1341 
1342   ASSERT_TRUE(android_init_anonymous_namespace(shared_libs.c_str(), nullptr)) << dlerror();
1343 
1344   android_namespace_t* ns_not_isolated =
1345           android_create_namespace("private",
1346                                    nullptr,
1347                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
1348                                    ANDROID_NAMESPACE_TYPE_REGULAR,
1349                                    nullptr,
1350                                    nullptr);
1351   ASSERT_TRUE(ns_not_isolated != nullptr) << dlerror();
1352   ASSERT_TRUE(android_link_namespaces(ns_not_isolated, nullptr, shared_libs.c_str())) << dlerror();
1353 
1354   android_namespace_t* ns_isolated =
1355           android_create_namespace("private_isolated1",
1356                                    nullptr,
1357                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
1358                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1359                                    nullptr,
1360                                    nullptr);
1361   ASSERT_TRUE(ns_isolated != nullptr) << dlerror();
1362   ASSERT_TRUE(android_link_namespaces(ns_isolated, nullptr, shared_libs.c_str())) << dlerror();
1363 
1364   android_namespace_t* ns_isolated2 =
1365           android_create_namespace("private_isolated2",
1366                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
1367                                    nullptr,
1368                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1369                                    GetTestLibRoot().c_str(),
1370                                    nullptr);
1371   ASSERT_TRUE(ns_isolated2 != nullptr) << dlerror();
1372   ASSERT_TRUE(android_link_namespaces(ns_isolated2, nullptr, shared_libs.c_str())) << dlerror();
1373 
1374   ASSERT_TRUE(dlopen(root_lib, RTLD_NOW) == nullptr);
1375   ASSERT_STREQ("dlopen failed: library \"libnstest_root_not_isolated.so\" not found", dlerror());
1376 
1377   std::string lib_private_external_path =
1378       GetTestLibRoot() + "/private_namespace_libs_external/libnstest_private_external.so";
1379 
1380   // Load lib_private_external_path to default namespace
1381   // (it should remain invisible for the isolated namespaces after this)
1382   void* handle = dlopen(lib_private_external_path.c_str(), RTLD_NOW);
1383   ASSERT_TRUE(handle != nullptr) << dlerror();
1384 
1385   android_dlextinfo extinfo;
1386   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1387   extinfo.library_namespace = ns_not_isolated;
1388 
1389   void* handle1 = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
1390   ASSERT_TRUE(handle1 != nullptr) << dlerror();
1391 
1392   extinfo.library_namespace = ns_isolated;
1393 
1394   void* handle2 = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
1395   ASSERT_TRUE(handle2 == nullptr);
1396   const char* error = dlerror();
1397   ASSERT_MATCH(error,
1398                R"(dlopen failed: library "libnstest_private_external.so" not found: needed by )"
1399                R"(\S+libnstest_root_not_isolated.so in namespace private_isolated1)");
1400 
1401   // Check dlopen by absolute path
1402   handle2 = android_dlopen_ext(lib_private_external_path.c_str(), RTLD_NOW, &extinfo);
1403   ASSERT_TRUE(handle2 == nullptr);
1404   ASSERT_EQ("dlopen failed: library \"" + lib_private_external_path + "\" needed"
1405             " or dlopened by \"" + android::base::GetExecutablePath() +  "\" is not accessible"
1406             " for the namespace \"private_isolated1\"", dlerror());
1407 
1408   extinfo.library_namespace = ns_isolated2;
1409 
1410   // this should work because isolation_path for private_isolated2 includes GetTestLibRoot()
1411   handle2 = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
1412   ASSERT_TRUE(handle2 != nullptr) << dlerror();
1413   dlclose(handle2);
1414 
1415   // Check dlopen by absolute path
1416   handle2 = android_dlopen_ext(lib_private_external_path.c_str(), RTLD_NOW, &extinfo);
1417   ASSERT_TRUE(handle2 != nullptr) << dlerror();
1418   dlclose(handle2);
1419 
1420   typedef const char* (*fn_t)();
1421   fn_t ns_get_local_string = reinterpret_cast<fn_t>(dlsym(handle1, "ns_get_local_string"));
1422   ASSERT_TRUE(ns_get_local_string != nullptr) << dlerror();
1423 
1424   ASSERT_STREQ("This string is local to root library", ns_get_local_string());
1425 
1426   fn_t ns_get_private_extern_string =
1427           reinterpret_cast<fn_t>(dlsym(handle1, "ns_get_private_extern_string"));
1428   ASSERT_TRUE(ns_get_private_extern_string != nullptr) << dlerror();
1429 
1430   ASSERT_STREQ("This string is from private namespace", ns_get_private_extern_string());
1431 
1432   fn_t ns_get_public_extern_string =
1433           reinterpret_cast<fn_t>(dlsym(handle1, "ns_get_public_extern_string"));
1434   ASSERT_TRUE(ns_get_public_extern_string != nullptr) << dlerror();
1435 
1436   ASSERT_STREQ("This string is from public namespace", ns_get_public_extern_string());
1437 
1438   fn_t ns_get_dlopened_string = reinterpret_cast<fn_t>(dlsym(handle1, "ns_get_dlopened_string"));
1439   ASSERT_TRUE(ns_get_dlopened_string != nullptr) << dlerror();
1440 
1441   ASSERT_STREQ("This string is from private namespace (dlopened library)", ns_get_dlopened_string());
1442 
1443   dlclose(handle1);
1444 }
1445 
TEST(dlext,ns_shared)1446 TEST(dlext, ns_shared) {
1447   static const char* root_lib = "libnstest_root_not_isolated.so";
1448   static const char* root_lib_isolated = "libnstest_root.so";
1449 
1450   std::string shared_libs = g_core_shared_libs + ":" + g_public_lib;
1451 
1452   // create a parent namespace to use instead of the default namespace. This is
1453   // to make this test be independent from the configuration of the default
1454   // namespace.
1455   android_namespace_t* ns_parent =
1456           android_create_namespace("parent",
1457                                    nullptr,
1458                                    nullptr,
1459                                    ANDROID_NAMESPACE_TYPE_REGULAR,
1460                                    nullptr,
1461                                    nullptr);
1462   ASSERT_TRUE(ns_parent != nullptr) << dlerror();
1463   ASSERT_TRUE(android_link_namespaces(ns_parent, nullptr, g_core_shared_libs.c_str())) << dlerror();
1464 
1465   android_dlextinfo extinfo;
1466   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1467   extinfo.library_namespace = ns_parent;
1468 
1469   const std::string lib_public_path = GetTestLibRoot() + "/public_namespace_libs/" + g_public_lib;
1470   void* handle_public = android_dlopen_ext(lib_public_path.c_str(), RTLD_NOW, &extinfo);
1471   ASSERT_TRUE(handle_public != nullptr) << dlerror();
1472 
1473   android_set_application_target_sdk_version(42U); // something > 23
1474 
1475   ASSERT_TRUE(android_init_anonymous_namespace(shared_libs.c_str(), nullptr)) << dlerror();
1476 
1477   // preload this library to the parent namespace to check if it
1478   // is shared later on.
1479   void* handle_dlopened =
1480           android_dlopen_ext((GetTestLibRoot() + "/private_namespace_libs/libnstest_dlopened.so").c_str(), RTLD_NOW, &extinfo);
1481   ASSERT_TRUE(handle_dlopened != nullptr) << dlerror();
1482 
1483   // create two child namespaces of 'ns_parent'. One with regular, the other
1484   // with isolated & shared.
1485   android_namespace_t* ns_not_isolated =
1486           android_create_namespace("private",
1487                                    nullptr,
1488                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
1489                                    ANDROID_NAMESPACE_TYPE_REGULAR,
1490                                    nullptr,
1491                                    ns_parent);
1492   ASSERT_TRUE(ns_not_isolated != nullptr) << dlerror();
1493   ASSERT_TRUE(android_link_namespaces(ns_not_isolated, ns_parent, g_public_lib)) << dlerror();
1494   ASSERT_TRUE(android_link_namespaces(ns_not_isolated, nullptr, g_core_shared_libs.c_str())) << dlerror();
1495 
1496   android_namespace_t* ns_isolated_shared =
1497           android_create_namespace("private_isolated_shared",
1498                                    nullptr,
1499                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
1500                                    ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_SHARED,
1501                                    nullptr,
1502                                    ns_parent);
1503   ASSERT_TRUE(ns_isolated_shared != nullptr) << dlerror();
1504   ASSERT_TRUE(android_link_namespaces(ns_isolated_shared, ns_parent, g_public_lib)) << dlerror();
1505   ASSERT_TRUE(android_link_namespaces(ns_isolated_shared, nullptr, g_core_shared_libs.c_str())) << dlerror();
1506 
1507   ASSERT_TRUE(android_dlopen_ext(root_lib, RTLD_NOW, &extinfo) == nullptr);
1508   ASSERT_STREQ("dlopen failed: library \"libnstest_root_not_isolated.so\" not found", dlerror());
1509 
1510   std::string lib_private_external_path =
1511       GetTestLibRoot() + "/private_namespace_libs_external/libnstest_private_external.so";
1512 
1513   // Load lib_private_external_path to the parent namespace
1514   // (it should remain invisible for the isolated namespaces after this)
1515   void* handle = android_dlopen_ext(lib_private_external_path.c_str(), RTLD_NOW, &extinfo);
1516   ASSERT_TRUE(handle != nullptr) << dlerror();
1517 
1518   extinfo.library_namespace = ns_not_isolated;
1519 
1520   void* handle1 = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
1521   ASSERT_TRUE(handle1 != nullptr) << dlerror();
1522 
1523   extinfo.library_namespace = ns_isolated_shared;
1524 
1525   void* handle2 = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
1526   ASSERT_TRUE(handle2 == nullptr);
1527   ASSERT_MATCH(dlerror(),
1528                R"(dlopen failed: library "libnstest_private_external.so" not found: needed by )"
1529                R"(\S+libnstest_root_not_isolated.so in namespace private_isolated_shared)");
1530 
1531   // Check dlopen by absolute path
1532   handle2 = android_dlopen_ext(lib_private_external_path.c_str(), RTLD_NOW, &extinfo);
1533   ASSERT_TRUE(handle2 == nullptr);
1534   ASSERT_EQ("dlopen failed: library \"" + lib_private_external_path + "\" needed"
1535             " or dlopened by \"" + android::base::GetExecutablePath() + "\" is not accessible"
1536             " for the namespace \"private_isolated_shared\"", dlerror());
1537 
1538   // load libnstest_root.so to shared namespace in order to check that everything is different
1539   // except shared libnstest_dlopened.so
1540 
1541   handle2 = android_dlopen_ext(root_lib_isolated, RTLD_NOW, &extinfo);
1542 
1543   typedef const char* (*fn_t)();
1544   fn_t ns_get_local_string = reinterpret_cast<fn_t>(dlsym(handle1, "ns_get_local_string"));
1545   ASSERT_TRUE(ns_get_local_string != nullptr) << dlerror();
1546   fn_t ns_get_local_string_shared = reinterpret_cast<fn_t>(dlsym(handle2, "ns_get_local_string"));
1547   ASSERT_TRUE(ns_get_local_string_shared != nullptr) << dlerror();
1548 
1549   ASSERT_STREQ("This string is local to root library", ns_get_local_string());
1550   ASSERT_STREQ("This string is local to root library", ns_get_local_string_shared());
1551   ASSERT_TRUE(ns_get_local_string() != ns_get_local_string_shared());
1552 
1553   fn_t ns_get_private_extern_string =
1554           reinterpret_cast<fn_t>(dlsym(handle1, "ns_get_private_extern_string"));
1555   ASSERT_TRUE(ns_get_private_extern_string != nullptr) << dlerror();
1556   fn_t ns_get_private_extern_string_shared =
1557           reinterpret_cast<fn_t>(dlsym(handle2, "ns_get_private_extern_string"));
1558   ASSERT_TRUE(ns_get_private_extern_string_shared() != nullptr) << dlerror();
1559 
1560   ASSERT_STREQ("This string is from private namespace", ns_get_private_extern_string());
1561   ASSERT_STREQ("This string is from private namespace", ns_get_private_extern_string_shared());
1562   ASSERT_TRUE(ns_get_private_extern_string() != ns_get_private_extern_string_shared());
1563 
1564   fn_t ns_get_public_extern_string =
1565           reinterpret_cast<fn_t>(dlsym(handle1, "ns_get_public_extern_string"));
1566   ASSERT_TRUE(ns_get_public_extern_string != nullptr) << dlerror();
1567   fn_t ns_get_public_extern_string_shared =
1568           reinterpret_cast<fn_t>(dlsym(handle2, "ns_get_public_extern_string"));
1569   ASSERT_TRUE(ns_get_public_extern_string_shared != nullptr) << dlerror();
1570 
1571   ASSERT_STREQ("This string is from public namespace", ns_get_public_extern_string());
1572   ASSERT_STREQ("This string is from public namespace", ns_get_public_extern_string_shared());
1573   ASSERT_TRUE(ns_get_public_extern_string() == ns_get_public_extern_string_shared());
1574 
1575   fn_t ns_get_dlopened_string = reinterpret_cast<fn_t>(dlsym(handle1, "ns_get_dlopened_string"));
1576   ASSERT_TRUE(ns_get_dlopened_string != nullptr) << dlerror();
1577   fn_t ns_get_dlopened_string_shared = reinterpret_cast<fn_t>(dlsym(handle2, "ns_get_dlopened_string"));
1578   ASSERT_TRUE(ns_get_dlopened_string_shared != nullptr) << dlerror();
1579   const char** ns_dlopened_string = static_cast<const char**>(dlsym(handle_dlopened, "g_private_dlopened_string"));
1580   ASSERT_TRUE(ns_dlopened_string != nullptr) << dlerror();
1581 
1582   ASSERT_STREQ("This string is from private namespace (dlopened library)", ns_get_dlopened_string());
1583   ASSERT_STREQ("This string is from private namespace (dlopened library)", *ns_dlopened_string);
1584   ASSERT_STREQ("This string is from private namespace (dlopened library)", ns_get_dlopened_string_shared());
1585   ASSERT_TRUE(ns_get_dlopened_string() != ns_get_dlopened_string_shared());
1586   ASSERT_TRUE(*ns_dlopened_string == ns_get_dlopened_string_shared());
1587 
1588   dlclose(handle1);
1589   dlclose(handle2);
1590 }
1591 
TEST(dlext,ns_shared_links_and_paths)1592 TEST(dlext, ns_shared_links_and_paths) {
1593   // Create parent namespace (isolated, not shared)
1594   android_namespace_t* ns_isolated =
1595           android_create_namespace("private_isolated",
1596                                    nullptr,
1597                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
1598                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1599                                    (GetTestLibRoot() + "/public_namespace_libs").c_str(),
1600                                    nullptr);
1601   ASSERT_TRUE(ns_isolated != nullptr) << dlerror();
1602   ASSERT_TRUE(android_link_namespaces(ns_isolated, nullptr, g_core_shared_libs.c_str())) << dlerror();
1603 
1604   // Create shared namespace with ns_isolated parent
1605   android_namespace_t* ns_shared =
1606           android_create_namespace("private_shared",
1607                                    nullptr,
1608                                    nullptr,
1609                                    ANDROID_NAMESPACE_TYPE_SHARED | ANDROID_NAMESPACE_TYPE_ISOLATED,
1610                                    nullptr,
1611                                    ns_isolated);
1612   ASSERT_TRUE(ns_shared != nullptr) << dlerror();
1613 
1614   // 1. Load a library in ns_shared to check that it has inherited
1615   // search path and the link to the default namespace.
1616   android_dlextinfo extinfo;
1617   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1618   extinfo.library_namespace = ns_shared;
1619 
1620   {
1621     void* handle = android_dlopen_ext("libnstest_private.so", RTLD_NOW, &extinfo);
1622     ASSERT_TRUE(handle != nullptr) << dlerror();
1623     const char** ns_private_extern_string = static_cast<const char**>(dlsym(handle, "g_private_extern_string"));
1624     ASSERT_TRUE(ns_private_extern_string != nullptr) << dlerror();
1625     ASSERT_STREQ("This string is from private namespace", *ns_private_extern_string);
1626 
1627     dlclose(handle);
1628   }
1629   // 2. Load another test library by absolute path to check that
1630   // it has inherited permitted_when_isolated_path
1631   {
1632     void* handle = android_dlopen_ext(
1633             (GetTestLibRoot() + "/public_namespace_libs/libnstest_public.so").c_str(),
1634             RTLD_NOW,
1635             &extinfo);
1636 
1637     ASSERT_TRUE(handle != nullptr) << dlerror();
1638     const char** ns_public_extern_string = static_cast<const char**>(dlsym(handle, "g_public_extern_string"));
1639     ASSERT_TRUE(ns_public_extern_string != nullptr) << dlerror();
1640     ASSERT_STREQ("This string is from public namespace", *ns_public_extern_string);
1641 
1642     dlclose(handle);
1643   }
1644 
1645   // 3. Check that it is still isolated.
1646   {
1647     void* handle = android_dlopen_ext(
1648             (GetTestLibRoot() + "/libtest_empty.so").c_str(),
1649             RTLD_NOW,
1650             &extinfo);
1651 
1652     ASSERT_TRUE(handle == nullptr);
1653   }
1654 }
1655 
TEST(dlext,ns_shared_dlclose)1656 TEST(dlext, ns_shared_dlclose) {
1657   android_set_application_target_sdk_version(42U); // something > 23
1658 
1659   ASSERT_TRUE(android_init_anonymous_namespace(g_core_shared_libs.c_str(), nullptr)) << dlerror();
1660 
1661   // preload this library to the default namespace to check if it
1662   // is shared later on.
1663   void* handle_dlopened =
1664           dlopen((GetTestLibRoot() + "/private_namespace_libs/libnstest_dlopened.so").c_str(), RTLD_NOW);
1665   ASSERT_TRUE(handle_dlopened != nullptr) << dlerror();
1666 
1667   android_namespace_t* ns_isolated_shared =
1668           android_create_namespace("private_isolated_shared",
1669                                    nullptr,
1670                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
1671                                    ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_SHARED,
1672                                    nullptr,
1673                                    nullptr);
1674   ASSERT_TRUE(ns_isolated_shared != nullptr) << dlerror();
1675   ASSERT_TRUE(android_link_namespaces(ns_isolated_shared, nullptr, g_core_shared_libs.c_str())) << dlerror();
1676 
1677   // Check if "libnstest_dlopened.so" is loaded (and the same)
1678   android_dlextinfo extinfo;
1679   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1680   extinfo.library_namespace = ns_isolated_shared;
1681 
1682   void* handle = android_dlopen_ext("libnstest_dlopened.so", RTLD_NOW | RTLD_NOLOAD, &extinfo);
1683   ASSERT_TRUE(handle != nullptr) << dlerror();
1684   ASSERT_TRUE(handle == handle_dlopened);
1685   dlclose(handle);
1686   dlclose(handle_dlopened);
1687 
1688   // And now check that the library cannot be found by soname (and is no longer loaded)
1689   handle = android_dlopen_ext("libnstest_dlopened.so", RTLD_NOW | RTLD_NOLOAD, &extinfo);
1690   ASSERT_TRUE(handle == nullptr)
1691       << "Error: libnstest_dlopened.so is still accessible in shared namespace";
1692 
1693   handle = android_dlopen_ext((GetTestLibRoot() + "/private_namespace_libs/libnstest_dlopened.so").c_str(),
1694                               RTLD_NOW | RTLD_NOLOAD, &extinfo);
1695   ASSERT_TRUE(handle == nullptr)
1696       << "Error: libnstest_dlopened.so is still accessible in shared namespace";
1697 
1698   handle = dlopen("libnstest_dlopened.so", RTLD_NOW | RTLD_NOLOAD);
1699   ASSERT_TRUE(handle == nullptr)
1700       << "Error: libnstest_dlopened.so is still accessible in default namespace";
1701 
1702   handle = dlopen((GetTestLibRoot() + "/private_namespace_libs/libnstest_dlopened.so").c_str(),
1703                   RTLD_NOW | RTLD_NOLOAD);
1704   ASSERT_TRUE(handle == nullptr)
1705       << "Error: libnstest_dlopened.so is still accessible in default namespace";
1706 
1707   // Now lets see if the soinfo area gets reused in the wrong way:
1708   // load a library to default namespace.
1709   const std::string lib_public_path = GetTestLibRoot() + "/public_namespace_libs/" + g_public_lib;
1710   void* handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW);
1711   ASSERT_TRUE(handle_public != nullptr) << dlerror();
1712 
1713   // try to find it in shared namespace
1714   handle = android_dlopen_ext(g_public_lib, RTLD_NOW | RTLD_NOLOAD, &extinfo);
1715   ASSERT_TRUE(handle == nullptr)
1716       << "Error: " << g_public_lib << " is accessible in shared namespace";
1717 }
1718 
TEST(dlext,ns_isolated_rtld_global)1719 TEST(dlext, ns_isolated_rtld_global) {
1720   static const char* root_lib = "libnstest_root.so";
1721   ASSERT_TRUE(android_init_anonymous_namespace(g_core_shared_libs.c_str(), nullptr));
1722 
1723   const std::string lib_public_path = GetTestLibRoot() + "/public_namespace_libs";
1724 
1725   android_namespace_t* ns1 =
1726           android_create_namespace("isolated1",
1727                                    nullptr,
1728                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
1729                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1730                                    lib_public_path.c_str(),
1731                                    nullptr);
1732   ASSERT_TRUE(ns1 != nullptr) << dlerror();
1733   ASSERT_TRUE(android_link_namespaces(ns1, nullptr, g_core_shared_libs.c_str())) << dlerror();
1734 
1735   android_namespace_t* ns2 =
1736           android_create_namespace("isolated2",
1737                                    nullptr,
1738                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
1739                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1740                                    lib_public_path.c_str(),
1741                                    nullptr);
1742   ASSERT_TRUE(ns2 != nullptr) << dlerror();
1743   ASSERT_TRUE(android_link_namespaces(ns2, nullptr, g_core_shared_libs.c_str())) << dlerror();
1744 
1745   android_dlextinfo extinfo;
1746   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1747   extinfo.library_namespace = ns1;
1748 
1749   void* handle_global = android_dlopen_ext((lib_public_path + "/" + g_public_lib).c_str(),
1750                                            RTLD_GLOBAL,
1751                                            &extinfo);
1752 
1753   ASSERT_TRUE(handle_global != nullptr) << dlerror();
1754 
1755   android_namespace_t* ns1_child =
1756           android_create_namespace("isolated1_child",
1757                                    nullptr,
1758                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
1759                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1760                                    nullptr,
1761                                    ns1);
1762 
1763   ASSERT_TRUE(ns1_child != nullptr) << dlerror();
1764   ASSERT_TRUE(android_link_namespaces(ns1_child, nullptr, g_core_shared_libs.c_str())) << dlerror();
1765 
1766   // Now - only ns1 and ns1 child should be able to dlopen root_lib
1767   // attempt to use ns2 should result in dlerror()
1768 
1769   // Check ns1_child first.
1770   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1771   extinfo.library_namespace = ns1_child;
1772 
1773   void* handle1 = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
1774   ASSERT_TRUE(handle1 != nullptr) << dlerror();
1775 
1776   // now ns1
1777   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1778   extinfo.library_namespace = ns1;
1779 
1780   handle1 = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
1781   ASSERT_TRUE(handle1 != nullptr) << dlerror();
1782 
1783   // and ns2 should fail
1784   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1785   extinfo.library_namespace = ns2;
1786 
1787   handle1 = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
1788   ASSERT_TRUE(handle1 == nullptr);
1789   ASSERT_MATCH(
1790       dlerror(),
1791       R"(dlopen failed: library "libnstest_public.so" not found: needed by \S+libnstest_root.so)"
1792       R"( in namespace isolated2)");
1793 }
1794 
TEST(dlext,ns_inaccessible_error_message)1795 TEST(dlext, ns_inaccessible_error_message) {
1796   // We set up 2 namespaces (a and b) and link a->b with a shared library
1797   // libtestshared.so. Then try to dlopen different library with the same
1798   // name from in namespace a. Note that library should not be accessible
1799   // in either namespace but since it's soname is in the list of shared libs
1800   // the linker will attempt to find it in linked namespace.
1801   //
1802   // Check the error message and make sure it mentions correct namespace name.
1803   ASSERT_TRUE(android_init_anonymous_namespace(g_core_shared_libs.c_str(), nullptr));
1804 
1805   android_namespace_t* ns_a =
1806           android_create_namespace("ns_a",
1807                                    nullptr,
1808                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
1809                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1810                                    nullptr,
1811                                    nullptr);
1812   ASSERT_TRUE(ns_a != nullptr) << dlerror();
1813   ASSERT_TRUE(android_link_namespaces(ns_a, nullptr, g_core_shared_libs.c_str())) << dlerror();
1814 
1815   android_namespace_t* ns_b =
1816           android_create_namespace("ns_b",
1817                                    nullptr,
1818                                    GetTestLibRoot().c_str(),
1819                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1820                                    nullptr,
1821                                    nullptr);
1822   ASSERT_TRUE(ns_b != nullptr) << dlerror();
1823   ASSERT_TRUE(android_link_namespaces(ns_b, nullptr, g_core_shared_libs.c_str())) << dlerror();
1824 
1825   ASSERT_TRUE(android_link_namespaces(ns_a, ns_b, "libtestshared.so")) << dlerror();
1826 
1827   android_dlextinfo extinfo;
1828   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1829   extinfo.library_namespace = ns_a;
1830 
1831   std::string library_path = GetTestLibRoot() + "/inaccessible_libs/libtestshared.so";
1832 
1833   void* handle = android_dlopen_ext(library_path.c_str(), RTLD_NOW, &extinfo);
1834   ASSERT_TRUE(handle == nullptr);
1835   std::string expected_dlerror =
1836       android::base::StringPrintf("dlopen failed: library \"%s\" needed or dlopened by \"%s\""
1837                                   " is not accessible for the namespace \"ns_a\"",
1838                                   library_path.c_str(),
1839                                   android::base::GetExecutablePath().c_str());
1840   ASSERT_EQ(expected_dlerror, dlerror());
1841 }
1842 
1843 extern "C" bool __loader_android_link_namespaces_all_libs(android_namespace_t* namespace_from,
1844                                                           android_namespace_t* namespace_to);
1845 
TEST(dlext,ns_link_namespaces_invalid_arguments)1846 TEST(dlext, ns_link_namespaces_invalid_arguments) {
1847   ASSERT_TRUE(android_init_anonymous_namespace(g_core_shared_libs.c_str(), nullptr));
1848 
1849   android_namespace_t* ns =
1850           android_create_namespace("private",
1851                                    nullptr,
1852                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
1853                                    ANDROID_NAMESPACE_TYPE_REGULAR,
1854                                    nullptr,
1855                                    nullptr);
1856   ASSERT_TRUE(ns != nullptr) << dlerror();
1857 
1858   // Test android_link_namespaces()
1859   ASSERT_FALSE(android_link_namespaces(nullptr, nullptr, "libc.so"));
1860   ASSERT_STREQ("android_link_namespaces failed: error linking namespaces: namespace_from is null.",
1861                dlerror());
1862 
1863   ASSERT_FALSE(android_link_namespaces(ns, nullptr, nullptr));
1864   ASSERT_STREQ("android_link_namespaces failed: "
1865                "error linking namespaces \"private\"->\"(default)\": "
1866                "the list of shared libraries is empty.", dlerror());
1867 
1868   ASSERT_FALSE(android_link_namespaces(ns, nullptr, ""));
1869   ASSERT_STREQ("android_link_namespaces failed: "
1870                "error linking namespaces \"private\"->\"(default)\": "
1871                "the list of shared libraries is empty.", dlerror());
1872 
1873   // Test __loader_android_link_namespaces_all_libs()
1874   ASSERT_FALSE(__loader_android_link_namespaces_all_libs(nullptr, nullptr));
1875   ASSERT_STREQ("android_link_namespaces_all_libs failed: "
1876                "error linking namespaces: namespace_from is null.", dlerror());
1877 
1878   ASSERT_FALSE(__loader_android_link_namespaces_all_libs(nullptr, ns));
1879   ASSERT_STREQ("android_link_namespaces_all_libs failed: "
1880                "error linking namespaces: namespace_from is null.", dlerror());
1881 
1882   ASSERT_FALSE(__loader_android_link_namespaces_all_libs(ns, nullptr));
1883   ASSERT_STREQ("android_link_namespaces_all_libs failed: "
1884                "error linking namespaces: namespace_to is null.", dlerror());
1885 }
1886 
TEST(dlext,ns_allow_all_shared_libs)1887 TEST(dlext, ns_allow_all_shared_libs) {
1888   ASSERT_TRUE(android_init_anonymous_namespace(g_core_shared_libs.c_str(), nullptr));
1889 
1890   android_namespace_t* ns_a =
1891           android_create_namespace("ns_a",
1892                                    nullptr,
1893                                    (GetTestLibRoot() + "/ns_a").c_str(),
1894                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1895                                    nullptr,
1896                                    nullptr);
1897   ASSERT_TRUE(ns_a != nullptr) << dlerror();
1898   ASSERT_TRUE(android_link_namespaces(ns_a, nullptr, g_core_shared_libs.c_str())) << dlerror();
1899 
1900   android_namespace_t* ns_b =
1901           android_create_namespace("ns_b",
1902                                    nullptr,
1903                                    (GetTestLibRoot() + "/ns_b").c_str(),
1904                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
1905                                    nullptr,
1906                                    nullptr);
1907   ASSERT_TRUE(ns_b != nullptr) << dlerror();
1908   ASSERT_TRUE(android_link_namespaces(ns_b, nullptr, g_core_shared_libs.c_str())) << dlerror();
1909 
1910   ASSERT_TRUE(android_link_namespaces(ns_b, ns_a, "libnstest_ns_a_public1.so")) << dlerror();
1911   ASSERT_TRUE(__loader_android_link_namespaces_all_libs(ns_a, ns_b)) << dlerror();
1912 
1913   // Load libs with android_dlopen_ext() from namespace b
1914   android_dlextinfo extinfo;
1915   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
1916   extinfo.library_namespace = ns_b;
1917 
1918   void* ns_b_handle1 = android_dlopen_ext("libnstest_ns_a_public1.so", RTLD_NOW, &extinfo);
1919   ASSERT_TRUE(ns_b_handle1 != nullptr) << dlerror();
1920 
1921   void* ns_b_handle1_internal =
1922       android_dlopen_ext("libnstest_ns_a_public1_internal.so", RTLD_NOW, &extinfo);
1923   ASSERT_TRUE(ns_b_handle1_internal == nullptr);
1924 
1925   void* ns_b_handle2 = android_dlopen_ext("libnstest_ns_b_public2.so", RTLD_NOW, &extinfo);
1926   ASSERT_TRUE(ns_b_handle2 != nullptr) << dlerror();
1927 
1928   void* ns_b_handle3 = android_dlopen_ext("libnstest_ns_b_public3.so", RTLD_NOW, &extinfo);
1929   ASSERT_TRUE(ns_b_handle3 != nullptr) << dlerror();
1930 
1931   // Load libs with android_dlopen_ext() from namespace a
1932   extinfo.library_namespace = ns_a;
1933 
1934   void* ns_a_handle1 = android_dlopen_ext("libnstest_ns_a_public1.so", RTLD_NOW, &extinfo);
1935   ASSERT_TRUE(ns_a_handle1 != nullptr) << dlerror();
1936 
1937   void* ns_a_handle1_internal =
1938       android_dlopen_ext("libnstest_ns_a_public1_internal.so", RTLD_NOW, &extinfo);
1939   ASSERT_TRUE(ns_a_handle1_internal != nullptr) << dlerror();
1940 
1941   void* ns_a_handle2 = android_dlopen_ext("libnstest_ns_b_public2.so", RTLD_NOW, &extinfo);
1942   ASSERT_TRUE(ns_a_handle2 != nullptr) << dlerror();
1943 
1944   void* ns_a_handle3 = android_dlopen_ext("libnstest_ns_b_public3.so", RTLD_NOW, &extinfo);
1945   ASSERT_TRUE(ns_a_handle3 != nullptr) << dlerror();
1946 
1947   // Compare the dlopen handle
1948   ASSERT_EQ(ns_b_handle1, ns_a_handle1);
1949   ASSERT_EQ(ns_b_handle2, ns_a_handle2);
1950   ASSERT_EQ(ns_b_handle3, ns_a_handle3);
1951 
1952   // Close libs
1953   dlclose(ns_b_handle1);
1954   dlclose(ns_b_handle2);
1955   dlclose(ns_b_handle3);
1956 
1957   dlclose(ns_a_handle1);
1958   dlclose(ns_a_handle1_internal);
1959   dlclose(ns_a_handle2);
1960   dlclose(ns_a_handle3);
1961 }
1962 
MapPflagsToProtFlags(uint32_t flags)1963 static inline int MapPflagsToProtFlags(uint32_t flags) {
1964   int prot_flags = 0;
1965   if (PF_X & flags) prot_flags |= PROT_EXEC;
1966   if (PF_W & flags) prot_flags |= PROT_WRITE;
1967   if (PF_R & flags) prot_flags |= PROT_READ;
1968   return prot_flags;
1969 }
1970 
TEST(dlext,ns_anonymous)1971 TEST(dlext, ns_anonymous) {
1972   static const char* root_lib = "libnstest_root.so";
1973   std::string shared_libs = g_core_shared_libs + ":" + g_public_lib;
1974 
1975   const std::string lib_public_path = GetTestLibRoot() + "/public_namespace_libs/" + g_public_lib;
1976   void* handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW);
1977 
1978   ASSERT_TRUE(handle_public != nullptr) << dlerror();
1979 
1980   ASSERT_TRUE(
1981           android_init_anonymous_namespace(shared_libs.c_str(),
1982                                            (GetTestLibRoot() + "/private_namespace_libs").c_str())
1983       ) << dlerror();
1984 
1985   android_namespace_t* ns =
1986           android_create_namespace("private",
1987                                    nullptr,
1988                                    (GetTestLibRoot() + "/private_namespace_libs").c_str(),
1989                                    ANDROID_NAMESPACE_TYPE_REGULAR,
1990                                    nullptr,
1991                                    nullptr);
1992 
1993   ASSERT_TRUE(ns != nullptr) << dlerror();
1994   ASSERT_TRUE(android_link_namespaces(ns, nullptr, shared_libs.c_str())) << dlerror();
1995 
1996   std::string private_library_absolute_path = GetTestLibRoot() + "/private_namespace_libs/" + root_lib;
1997 
1998   android_dlextinfo extinfo;
1999   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
2000   extinfo.library_namespace = ns;
2001 
2002   // we are going to copy this library to anonymous mmap and call the copy of ns_get_dlopened_string
2003   void* handle = android_dlopen_ext(private_library_absolute_path.c_str(), RTLD_NOW, &extinfo);
2004   ASSERT_TRUE(handle != nullptr) << dlerror();
2005 
2006   uintptr_t ns_get_dlopened_string_addr =
2007       reinterpret_cast<uintptr_t>(dlsym(handle, "ns_get_dlopened_string"));
2008   ASSERT_TRUE(ns_get_dlopened_string_addr != 0) << dlerror();
2009   typedef const char* (*fn_t)();
2010   fn_t ns_get_dlopened_string_private = reinterpret_cast<fn_t>(ns_get_dlopened_string_addr);
2011 
2012   Dl_info private_library_info;
2013   ASSERT_NE(dladdr(reinterpret_cast<void*>(ns_get_dlopened_string_addr), &private_library_info), 0)
2014       << dlerror();
2015   std::vector<map_record> maps_to_copy;
2016   bool has_executable_segment = false;
2017   uintptr_t addr_start = 0;
2018   uintptr_t addr_end = 0;
2019   std::tuple dl_iterate_arg = {&private_library_info, &maps_to_copy, &has_executable_segment,
2020                                &addr_start, &addr_end};
2021   ASSERT_EQ(
2022       1, dl_iterate_phdr(
2023              [](dl_phdr_info* info, size_t /*size*/, void* data) -> int {
2024                auto [private_library_info, maps_to_copy, has_executable_segment, addr_start,
2025                      addr_end] = *reinterpret_cast<decltype(dl_iterate_arg)*>(data);
2026                if (info->dlpi_addr != reinterpret_cast<ElfW(Addr)>(private_library_info->dli_fbase))
2027                  return 0;
2028 
2029                for (size_t i = 0; i < info->dlpi_phnum; ++i) {
2030                  const ElfW(Phdr)* phdr = info->dlpi_phdr + i;
2031                  if (phdr->p_type != PT_LOAD) continue;
2032                  *has_executable_segment |= phdr->p_flags & PF_X;
2033                  uintptr_t mapping_start = page_start(info->dlpi_addr + phdr->p_vaddr);
2034                  uintptr_t mapping_end = page_end(info->dlpi_addr + phdr->p_vaddr + phdr->p_memsz);
2035                  if (*addr_start == 0 || mapping_start < *addr_start) *addr_start = mapping_start;
2036                  if (*addr_end == 0 || mapping_end > *addr_end) *addr_end = mapping_end;
2037                  maps_to_copy->push_back({
2038                      .addr_start = mapping_start,
2039                      .addr_end = mapping_end,
2040                      .perms = MapPflagsToProtFlags(phdr->p_flags),
2041                  });
2042                }
2043                return 1;
2044              },
2045              &dl_iterate_arg));
2046 
2047   // Some validity checks.
2048   ASSERT_NE(maps_to_copy.size(), 0u);
2049   ASSERT_TRUE(addr_start > 0);
2050   ASSERT_TRUE(addr_end > 0);
2051   ASSERT_TRUE(ns_get_dlopened_string_addr > addr_start);
2052   ASSERT_TRUE(ns_get_dlopened_string_addr < addr_end);
2053 
2054   if (!has_executable_segment) {
2055     // For some natively bridged environments this code might be missing
2056     // the executable flag. This is because the guest code is not supposed
2057     // to be executed directly and making it non-executable is more secure.
2058     // In this case we assume the segment with the function is executable.
2059     for (auto& rec : maps_to_copy) {
2060       if (ns_get_dlopened_string_addr >= rec.addr_start &&
2061           ns_get_dlopened_string_addr < rec.addr_end) {
2062         ASSERT_TRUE((rec.perms & PROT_WRITE) == 0);
2063         rec.perms |= PROT_EXEC;
2064         break;
2065       }
2066     }
2067   }
2068 
2069   // copy
2070   uintptr_t reserved_addr = reinterpret_cast<uintptr_t>(mmap(nullptr, addr_end - addr_start,
2071                                                              PROT_NONE, MAP_ANON | MAP_PRIVATE,
2072                                                              -1, 0));
2073   ASSERT_TRUE(reinterpret_cast<void*>(reserved_addr) != MAP_FAILED);
2074 
2075   struct stat file_stat;
2076   int ret = TEMP_FAILURE_RETRY(stat(private_library_absolute_path.c_str(), &file_stat));
2077   ASSERT_EQ(ret, 0) << "Failed to stat library";
2078   size_t file_size = file_stat.st_size;
2079 
2080   {
2081     // Disable MTE while copying the PROT_MTE-protected global variables from
2082     // the existing mappings. We don't really care about turning on PROT_MTE for
2083     // the new copy of the mappings, as this isn't the behaviour under test and
2084     // tags will be ignored. This only applies for MTE-enabled devices.
2085     ScopedDisableMTE disable_mte_for_copying_global_variables;
2086     for (const auto& rec : maps_to_copy) {
2087       uintptr_t offset = rec.addr_start - addr_start;
2088       size_t size = rec.addr_end - rec.addr_start;
2089       void* addr = reinterpret_cast<void*>(reserved_addr + offset);
2090       void* map =
2091           mmap(addr, size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0);
2092       ASSERT_TRUE(map != MAP_FAILED);
2093       // Attempting the below memcpy from a portion of the map that is off the end of
2094       // the backing file will cause the kernel to throw a SIGBUS
2095       size_t _size =
2096           ::android::procinfo::MappedFileSize(rec.addr_start, rec.addr_end, rec.offset, file_size);
2097       memcpy(map, reinterpret_cast<void*>(rec.addr_start), _size);
2098       mprotect(map, size, rec.perms);
2099     }
2100   }
2101 
2102   // call the function copy
2103   uintptr_t ns_get_dlopened_string_offset  = ns_get_dlopened_string_addr - addr_start;
2104   fn_t ns_get_dlopened_string_anon = reinterpret_cast<fn_t>(reserved_addr + ns_get_dlopened_string_offset);
2105   ASSERT_STREQ("This string is from private namespace (dlopened library)",
2106                ns_get_dlopened_string_anon());
2107 
2108   // They should belong to different namespaces (private and anonymous)
2109   ASSERT_STREQ("This string is from private namespace (dlopened library)",
2110                ns_get_dlopened_string_private());
2111 
2112   ASSERT_TRUE(ns_get_dlopened_string_anon() != ns_get_dlopened_string_private());
2113 }
2114 
TEST(dlext,ns_hidden_child)2115 TEST(dlext, ns_hidden_child) {
2116   ExecTestHelper eth;
2117 
2118   std::string helper = GetTestLibRoot() + "/ns_hidden_child_helper";
2119   std::string app_ns_dir = GetTestLibRoot() + "/ns_hidden_child_app";
2120   eth.SetArgs({ helper.c_str(), app_ns_dir.c_str(), nullptr });
2121 
2122   // Add the main libns_hidden_child_*.so libraries to the search path of the default namespace.
2123   std::string env = "LD_LIBRARY_PATH=" + GetTestLibRoot();
2124   eth.SetEnv({ env.c_str(), nullptr });
2125 
2126   eth.Run([&]() { execve(helper.c_str(), eth.GetArgs(), eth.GetEnv()); }, 0,
2127           "public_function is non-null\n"
2128           "internal_function is null\n");
2129 }
2130 
TEST(dlext,dlopen_handle_value_platform)2131 TEST(dlext, dlopen_handle_value_platform) {
2132   void* handle = dlopen("libtest_dlsym_from_this.so", RTLD_NOW | RTLD_LOCAL);
2133   ASSERT_TRUE((reinterpret_cast<uintptr_t>(handle) & 1) != 0)
2134           << "dlopen should return odd value for the handle";
2135   dlclose(handle);
2136 }
2137 
TEST(dlext,dlopen_handle_value_app_compat)2138 TEST(dlext, dlopen_handle_value_app_compat) {
2139   android_set_application_target_sdk_version(23);
2140   void* handle = dlopen("libtest_dlsym_from_this.so", RTLD_NOW | RTLD_LOCAL);
2141   ASSERT_TRUE(reinterpret_cast<uintptr_t>(handle) % sizeof(uintptr_t) == 0)
2142           << "dlopen should return valid pointer";
2143   dlclose(handle);
2144 }
2145