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