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 <errno.h>
21 #include <fcntl.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <android/dlext.h>
26 #include <sys/mman.h>
27 #include <sys/types.h>
28 #include <sys/wait.h>
29 
30 #include <pagemap/pagemap.h>
31 
32 
33 #define ASSERT_DL_NOTNULL(ptr) \
34     ASSERT_TRUE(ptr != nullptr) << "dlerror: " << dlerror()
35 
36 #define ASSERT_DL_ZERO(i) \
37     ASSERT_EQ(0, i) << "dlerror: " << dlerror()
38 
39 #define ASSERT_NOERROR(i) \
40     ASSERT_NE(-1, i) << "errno: " << strerror(errno)
41 
42 
43 typedef int (*fn)(void);
44 #define LIBNAME "libdlext_test.so"
45 #define LIBNAME_NORELRO "libdlext_test_norelro.so"
46 #define LIBSIZE 1024*1024 // how much address space to reserve for it
47 
48 #if defined(__LP64__)
49 #define LIBPATH_PREFIX "%s/nativetest64/libdlext_test_fd/"
50 #else
51 #define LIBPATH_PREFIX "%s/nativetest/libdlext_test_fd/"
52 #endif
53 
54 #define LIBPATH LIBPATH_PREFIX "libdlext_test_fd.so"
55 #define LIBZIPPATH LIBPATH_PREFIX "libdlext_test_fd_zipaligned.zip"
56 
57 #define LIBZIP_OFFSET 2*PAGE_SIZE
58 
59 class DlExtTest : public ::testing::Test {
60 protected:
SetUp()61   virtual void SetUp() {
62     handle_ = nullptr;
63     // verify that we don't have the library loaded already
64     void* h = dlopen(LIBNAME, RTLD_NOW | RTLD_NOLOAD);
65     ASSERT_TRUE(h == nullptr);
66     h = dlopen(LIBNAME_NORELRO, RTLD_NOW | RTLD_NOLOAD);
67     ASSERT_TRUE(h == nullptr);
68     // call dlerror() to swallow the error, and check it was the one we wanted
69     ASSERT_STREQ("dlopen failed: library \"" LIBNAME_NORELRO "\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
70   }
71 
TearDown()72   virtual void TearDown() {
73     if (handle_ != nullptr) {
74       ASSERT_DL_ZERO(dlclose(handle_));
75     }
76   }
77 
78   void* handle_;
79 };
80 
TEST_F(DlExtTest,ExtInfoNull)81 TEST_F(DlExtTest, ExtInfoNull) {
82   handle_ = android_dlopen_ext(LIBNAME, RTLD_NOW, nullptr);
83   ASSERT_DL_NOTNULL(handle_);
84   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
85   ASSERT_DL_NOTNULL(f);
86   EXPECT_EQ(4, f());
87 }
88 
TEST_F(DlExtTest,ExtInfoNoFlags)89 TEST_F(DlExtTest, ExtInfoNoFlags) {
90   android_dlextinfo extinfo;
91   extinfo.flags = 0;
92   handle_ = android_dlopen_ext(LIBNAME, RTLD_NOW, &extinfo);
93   ASSERT_DL_NOTNULL(handle_);
94   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
95   ASSERT_DL_NOTNULL(f);
96   EXPECT_EQ(4, f());
97 }
98 
TEST_F(DlExtTest,ExtInfoUseFd)99 TEST_F(DlExtTest, ExtInfoUseFd) {
100   const char* android_data = getenv("ANDROID_DATA");
101   ASSERT_TRUE(android_data != nullptr);
102   char lib_path[PATH_MAX];
103   snprintf(lib_path, sizeof(lib_path), LIBPATH, android_data);
104 
105   android_dlextinfo extinfo;
106   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD;
107   extinfo.library_fd = TEMP_FAILURE_RETRY(open(lib_path, O_RDONLY | O_CLOEXEC));
108   ASSERT_TRUE(extinfo.library_fd != -1);
109   handle_ = android_dlopen_ext(lib_path, RTLD_NOW, &extinfo);
110   ASSERT_DL_NOTNULL(handle_);
111   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
112   ASSERT_DL_NOTNULL(f);
113   EXPECT_EQ(4, f());
114 }
115 
TEST_F(DlExtTest,ExtInfoUseFdWithOffset)116 TEST_F(DlExtTest, ExtInfoUseFdWithOffset) {
117   const char* android_data = getenv("ANDROID_DATA");
118   ASSERT_TRUE(android_data != nullptr);
119 
120   char lib_path[PATH_MAX];
121   snprintf(lib_path, sizeof(lib_path), LIBZIPPATH, android_data);
122 
123   android_dlextinfo extinfo;
124   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD | ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET;
125   extinfo.library_fd = TEMP_FAILURE_RETRY(open(lib_path, O_RDONLY | O_CLOEXEC));
126   extinfo.library_fd_offset = LIBZIP_OFFSET;
127 
128   handle_ = android_dlopen_ext(lib_path, RTLD_NOW, &extinfo);
129   ASSERT_DL_NOTNULL(handle_);
130 
131   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
132   ASSERT_DL_NOTNULL(f);
133   EXPECT_EQ(4, f());
134 }
135 
TEST_F(DlExtTest,ExtInfoUseFdWithInvalidOffset)136 TEST_F(DlExtTest, ExtInfoUseFdWithInvalidOffset) {
137   const char* android_data = getenv("ANDROID_DATA");
138   ASSERT_TRUE(android_data != nullptr);
139 
140   char lib_path[PATH_MAX];
141   snprintf(lib_path, sizeof(lib_path), LIBZIPPATH, android_data);
142 
143   android_dlextinfo extinfo;
144   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD | ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET;
145   extinfo.library_fd = TEMP_FAILURE_RETRY(open(lib_path, O_RDONLY | O_CLOEXEC));
146   extinfo.library_fd_offset = 17;
147 
148   handle_ = android_dlopen_ext("libname_placeholder", RTLD_NOW, &extinfo);
149   ASSERT_TRUE(handle_ == nullptr);
150   ASSERT_STREQ("dlopen failed: file offset for the library \"libname_placeholder\" is not page-aligned: 17", dlerror());
151 
152   extinfo.library_fd_offset = (5LL<<58) + PAGE_SIZE;
153   handle_ = android_dlopen_ext("libname_placeholder", RTLD_NOW, &extinfo);
154 
155   ASSERT_TRUE(handle_ == nullptr);
156   // TODO: Better error message when reading with offset > file_size
157   ASSERT_STREQ("dlopen failed: \"libname_placeholder\" has bad ELF magic", dlerror());
158 
159   close(extinfo.library_fd);
160 }
161 
TEST_F(DlExtTest,ExtInfoUseOffsetWihtoutFd)162 TEST_F(DlExtTest, ExtInfoUseOffsetWihtoutFd) {
163   android_dlextinfo extinfo;
164   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET;
165   extinfo.library_fd_offset = LIBZIP_OFFSET;
166 
167   handle_ = android_dlopen_ext("/some/lib/that/does_not_exist", RTLD_NOW, &extinfo);
168   ASSERT_TRUE(handle_ == nullptr);
169   ASSERT_STREQ("dlopen failed: invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without ANDROID_DLEXT_USE_LIBRARY_FD): 0x20", dlerror());
170 }
171 
TEST_F(DlExtTest,Reserved)172 TEST_F(DlExtTest, Reserved) {
173   void* start = mmap(nullptr, LIBSIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS,
174                      -1, 0);
175   ASSERT_TRUE(start != MAP_FAILED);
176   android_dlextinfo extinfo;
177   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS;
178   extinfo.reserved_addr = start;
179   extinfo.reserved_size = LIBSIZE;
180   handle_ = android_dlopen_ext(LIBNAME, RTLD_NOW, &extinfo);
181   ASSERT_DL_NOTNULL(handle_);
182   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
183   ASSERT_DL_NOTNULL(f);
184   EXPECT_GE(f, start);
185   EXPECT_LT(reinterpret_cast<void*>(f),
186             reinterpret_cast<char*>(start) + LIBSIZE);
187   EXPECT_EQ(4, f());
188 }
189 
TEST_F(DlExtTest,ReservedTooSmall)190 TEST_F(DlExtTest, ReservedTooSmall) {
191   void* start = mmap(nullptr, PAGE_SIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS,
192                      -1, 0);
193   ASSERT_TRUE(start != MAP_FAILED);
194   android_dlextinfo extinfo;
195   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS;
196   extinfo.reserved_addr = start;
197   extinfo.reserved_size = PAGE_SIZE;
198   handle_ = android_dlopen_ext(LIBNAME, RTLD_NOW, &extinfo);
199   EXPECT_EQ(nullptr, handle_);
200 }
201 
TEST_F(DlExtTest,ReservedHint)202 TEST_F(DlExtTest, ReservedHint) {
203   void* start = mmap(nullptr, LIBSIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS,
204                      -1, 0);
205   ASSERT_TRUE(start != MAP_FAILED);
206   android_dlextinfo extinfo;
207   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS_HINT;
208   extinfo.reserved_addr = start;
209   extinfo.reserved_size = LIBSIZE;
210   handle_ = android_dlopen_ext(LIBNAME, RTLD_NOW, &extinfo);
211   ASSERT_DL_NOTNULL(handle_);
212   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
213   ASSERT_DL_NOTNULL(f);
214   EXPECT_GE(f, start);
215   EXPECT_LT(reinterpret_cast<void*>(f),
216             reinterpret_cast<char*>(start) + LIBSIZE);
217   EXPECT_EQ(4, f());
218 }
219 
TEST_F(DlExtTest,ReservedHintTooSmall)220 TEST_F(DlExtTest, ReservedHintTooSmall) {
221   void* start = mmap(nullptr, PAGE_SIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS,
222                      -1, 0);
223   ASSERT_TRUE(start != MAP_FAILED);
224   android_dlextinfo extinfo;
225   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS_HINT;
226   extinfo.reserved_addr = start;
227   extinfo.reserved_size = PAGE_SIZE;
228   handle_ = android_dlopen_ext(LIBNAME, RTLD_NOW, &extinfo);
229   ASSERT_DL_NOTNULL(handle_);
230   fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
231   ASSERT_DL_NOTNULL(f);
232   EXPECT_TRUE(f < start || (reinterpret_cast<void*>(f) >=
233                             reinterpret_cast<char*>(start) + PAGE_SIZE));
234   EXPECT_EQ(4, f());
235 }
236 
237 class DlExtRelroSharingTest : public DlExtTest {
238 protected:
SetUp()239   virtual void SetUp() {
240     DlExtTest::SetUp();
241     void* start = mmap(nullptr, LIBSIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS,
242                        -1, 0);
243     ASSERT_TRUE(start != MAP_FAILED);
244     extinfo_.flags = ANDROID_DLEXT_RESERVED_ADDRESS;
245     extinfo_.reserved_addr = start;
246     extinfo_.reserved_size = LIBSIZE;
247     extinfo_.relro_fd = -1;
248 
249     const char* android_data = getenv("ANDROID_DATA");
250     ASSERT_TRUE(android_data != nullptr);
251     snprintf(relro_file_, sizeof(relro_file_), "%s/local/tmp/libdlext_test.relro", android_data);
252   }
253 
TearDown()254   virtual void TearDown() {
255     DlExtTest::TearDown();
256     if (extinfo_.relro_fd != -1) {
257       ASSERT_NOERROR(close(extinfo_.relro_fd));
258     }
259   }
260 
CreateRelroFile(const char * lib)261   void CreateRelroFile(const char* lib) {
262     int relro_fd = open(relro_file_, O_CREAT | O_RDWR | O_TRUNC, 0644);
263     ASSERT_NOERROR(relro_fd);
264 
265     pid_t pid = fork();
266     if (pid == 0) {
267       // child process
268       extinfo_.flags |= ANDROID_DLEXT_WRITE_RELRO;
269       extinfo_.relro_fd = relro_fd;
270       void* handle = android_dlopen_ext(lib, RTLD_NOW, &extinfo_);
271       if (handle == nullptr) {
272         fprintf(stderr, "in child: %s\n", dlerror());
273         exit(1);
274       }
275       exit(0);
276     }
277 
278     // continuing in parent
279     ASSERT_NOERROR(close(relro_fd));
280     ASSERT_NOERROR(pid);
281     int status;
282     ASSERT_EQ(pid, waitpid(pid, &status, 0));
283     ASSERT_TRUE(WIFEXITED(status));
284     ASSERT_EQ(0, WEXITSTATUS(status));
285 
286     // reopen file for reading so it can be used
287     relro_fd = open(relro_file_, O_RDONLY);
288     ASSERT_NOERROR(relro_fd);
289     extinfo_.flags |= ANDROID_DLEXT_USE_RELRO;
290     extinfo_.relro_fd = relro_fd;
291   }
292 
TryUsingRelro(const char * lib)293   void TryUsingRelro(const char* lib) {
294     handle_ = android_dlopen_ext(lib, RTLD_NOW, &extinfo_);
295     ASSERT_DL_NOTNULL(handle_);
296     fn f = reinterpret_cast<fn>(dlsym(handle_, "getRandomNumber"));
297     ASSERT_DL_NOTNULL(f);
298     EXPECT_EQ(4, f());
299   }
300 
301   void SpawnChildrenAndMeasurePss(const char* lib, bool share_relro, size_t* pss_out);
302 
303   android_dlextinfo extinfo_;
304   char relro_file_[PATH_MAX];
305 };
306 
TEST_F(DlExtRelroSharingTest,ChildWritesGoodData)307 TEST_F(DlExtRelroSharingTest, ChildWritesGoodData) {
308   ASSERT_NO_FATAL_FAILURE(CreateRelroFile(LIBNAME));
309   ASSERT_NO_FATAL_FAILURE(TryUsingRelro(LIBNAME));
310 }
311 
TEST_F(DlExtRelroSharingTest,ChildWritesNoRelro)312 TEST_F(DlExtRelroSharingTest, ChildWritesNoRelro) {
313   ASSERT_NO_FATAL_FAILURE(CreateRelroFile(LIBNAME_NORELRO));
314   ASSERT_NO_FATAL_FAILURE(TryUsingRelro(LIBNAME_NORELRO));
315 }
316 
TEST_F(DlExtRelroSharingTest,RelroFileEmpty)317 TEST_F(DlExtRelroSharingTest, RelroFileEmpty) {
318   int relro_fd = open(relro_file_, O_CREAT | O_RDWR | O_TRUNC, 0644);
319   ASSERT_NOERROR(relro_fd);
320   ASSERT_NOERROR(close(relro_fd));
321 
322   ASSERT_NO_FATAL_FAILURE(TryUsingRelro(LIBNAME));
323 }
324 
TEST_F(DlExtRelroSharingTest,VerifyMemorySaving)325 TEST_F(DlExtRelroSharingTest, VerifyMemorySaving) {
326   ASSERT_NO_FATAL_FAILURE(CreateRelroFile(LIBNAME));
327   int relro_fd = open(relro_file_, O_RDONLY);
328   ASSERT_NOERROR(relro_fd);
329   extinfo_.flags |= ANDROID_DLEXT_USE_RELRO;
330   extinfo_.relro_fd = relro_fd;
331   int pipefd[2];
332   ASSERT_NOERROR(pipe(pipefd));
333 
334   size_t without_sharing, with_sharing;
335   ASSERT_NO_FATAL_FAILURE(SpawnChildrenAndMeasurePss(LIBNAME, false, &without_sharing));
336   ASSERT_NO_FATAL_FAILURE(SpawnChildrenAndMeasurePss(LIBNAME, true, &with_sharing));
337 
338   // We expect the sharing to save at least 10% of the total PSS. In practice
339   // it saves 40%+ for this test.
340   size_t expected_size = without_sharing - (without_sharing/10);
341   EXPECT_LT(with_sharing, expected_size);
342 }
343 
getPss(pid_t pid,size_t * pss_out)344 void getPss(pid_t pid, size_t* pss_out) {
345   pm_kernel_t* kernel;
346   ASSERT_EQ(0, pm_kernel_create(&kernel));
347 
348   pm_process_t* process;
349   ASSERT_EQ(0, pm_process_create(kernel, pid, &process));
350 
351   pm_map_t** maps;
352   size_t num_maps;
353   ASSERT_EQ(0, pm_process_maps(process, &maps, &num_maps));
354 
355   size_t total_pss = 0;
356   for (size_t i = 0; i < num_maps; i++) {
357     pm_memusage_t usage;
358     ASSERT_EQ(0, pm_map_usage(maps[i], &usage));
359     total_pss += usage.pss;
360   }
361   *pss_out = total_pss;
362 
363   free(maps);
364   pm_process_destroy(process);
365   pm_kernel_destroy(kernel);
366 }
367 
SpawnChildrenAndMeasurePss(const char * lib,bool share_relro,size_t * pss_out)368 void DlExtRelroSharingTest::SpawnChildrenAndMeasurePss(const char* lib, bool share_relro,
369                                                        size_t* pss_out) {
370   const int CHILDREN = 20;
371 
372   // Create children
373   pid_t childpid[CHILDREN];
374   int childpipe[CHILDREN];
375   for (int i=0; i<CHILDREN; ++i) {
376     char read_buf;
377     int child_done_pipe[2], parent_done_pipe[2];
378     ASSERT_NOERROR(pipe(child_done_pipe));
379     ASSERT_NOERROR(pipe(parent_done_pipe));
380 
381     pid_t child = fork();
382     if (child == 0) {
383       // close the 'wrong' ends of the pipes in the child
384       close(child_done_pipe[0]);
385       close(parent_done_pipe[1]);
386 
387       // open the library
388       void* handle;
389       if (share_relro) {
390         handle = android_dlopen_ext(lib, RTLD_NOW, &extinfo_);
391       } else {
392         handle = dlopen(lib, RTLD_NOW);
393       }
394       if (handle == nullptr) {
395         fprintf(stderr, "in child: %s\n", dlerror());
396         exit(1);
397       }
398 
399       // close write end of child_done_pipe to signal the parent that we're done.
400       close(child_done_pipe[1]);
401 
402       // wait for the parent to close parent_done_pipe, then exit
403       read(parent_done_pipe[0], &read_buf, 1);
404       exit(0);
405     }
406 
407     ASSERT_NOERROR(child);
408 
409     // close the 'wrong' ends of the pipes in the parent
410     close(child_done_pipe[1]);
411     close(parent_done_pipe[0]);
412 
413     // wait for the child to be done
414     read(child_done_pipe[0], &read_buf, 1);
415     close(child_done_pipe[0]);
416 
417     // save the child's pid and the parent_done_pipe
418     childpid[i] = child;
419     childpipe[i] = parent_done_pipe[1];
420   }
421 
422   // Sum the PSS of all the children
423   size_t total_pss = 0;
424   for (int i=0; i<CHILDREN; ++i) {
425     size_t child_pss;
426     ASSERT_NO_FATAL_FAILURE(getPss(childpid[i], &child_pss));
427     total_pss += child_pss;
428   }
429   *pss_out = total_pss;
430 
431   // Close pipes and wait for children to exit
432   for (int i=0; i<CHILDREN; ++i) {
433     ASSERT_NOERROR(close(childpipe[i]));
434   }
435   for (int i=0; i<CHILDREN; ++i) {
436     int status;
437     ASSERT_EQ(childpid[i], waitpid(childpid[i], &status, 0));
438     ASSERT_TRUE(WIFEXITED(status));
439     ASSERT_EQ(0, WEXITSTATUS(status));
440   }
441 }
442