1 // Copyright 2020 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <link.h>
6 #include <sys/mman.h>
7 #include <sys/prctl.h>
8 #include <sys/utsname.h>
9
10 #include "base/android/linker/linker_jni.h"
11 #include "base/files/scoped_file.h"
12 #include "base/logging.h"
13 #include "base/system/sys_info.h"
14 #include "testing/gtest/include/gtest/gtest.h"
15
16 extern char __executable_start;
17
18 extern "C" {
19
20 // This function is exported by the dynamic linker but never declared in any
21 // official header for some architecture/version combinations.
22 int dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data),
23 void* data) __attribute__((weak_import));
24
25 } // extern "C"
26
27 namespace chromium_android_linker {
28
29 namespace {
30
31 // Implements the old method of finding library and RELRO ranges by providing a
32 // callback for use with dl_iterate_phdr(3). Data from the field has shown that
33 // this method makes library loading significantly slower than
34 // android_dlopen_ext(), it was replaced by the exuivalent one:
35 // NativeLibInfo::FindRelroAndLibraryRangesInElf().
36 class LibraryRangeFinder {
37 public:
LibraryRangeFinder(uintptr_t address)38 explicit LibraryRangeFinder(uintptr_t address) : load_address_(address) {}
39
load_address() const40 uintptr_t load_address() const { return load_address_; }
load_size() const41 size_t load_size() const { return load_size_; }
relro_start() const42 uintptr_t relro_start() const { return relro_start_; }
relro_size() const43 size_t relro_size() const { return relro_size_; }
44
45 static int VisitLibraryPhdrs(dl_phdr_info* info,
46 [[maybe_unused]] size_t size,
47 void* data);
48
49 private:
50 uintptr_t load_address_;
51 size_t load_size_ = 0;
52 uintptr_t relro_start_ = 0;
53 size_t relro_size_ = 0;
54 };
55
56 // Callback for dl_iterate_phdr(). From program headers (phdr(s)) of a loaded
57 // library determines its load address, and in case it is equal to
58 // |load_address()|, extracts the RELRO and size information from
59 // corresponding phdr(s).
60 // static
VisitLibraryPhdrs(dl_phdr_info * info,size_t size,void * data)61 int LibraryRangeFinder::VisitLibraryPhdrs(dl_phdr_info* info,
62 [[maybe_unused]] size_t size,
63 void* data) {
64 auto* finder = reinterpret_cast<LibraryRangeFinder*>(data);
65 ElfW(Addr) lookup_address = static_cast<ElfW(Addr)>(finder->load_address());
66
67 // Use max and min vaddr to compute the library's load size.
68 auto min_vaddr = std::numeric_limits<ElfW(Addr)>::max();
69 ElfW(Addr) max_vaddr = 0;
70 ElfW(Addr) min_relro_vaddr = ~0;
71 ElfW(Addr) max_relro_vaddr = 0;
72
73 bool is_matching = false;
74 for (int i = 0; i < info->dlpi_phnum; ++i) {
75 const ElfW(Phdr)* phdr = &info->dlpi_phdr[i];
76 switch (phdr->p_type) {
77 case PT_LOAD:
78 // See if this segment's load address matches the value passed to
79 // android_dlopen_ext as |extinfo.reserved_addr|.
80 //
81 // Here and below, the virtual address in memory is computed by
82 // address == info->dlpi_addr + program_header->p_vaddr
83 // that is, the p_vaddr fields is relative to the object base address.
84 // See dl_iterate_phdr(3) for details.
85 if (lookup_address == info->dlpi_addr + phdr->p_vaddr)
86 is_matching = true;
87
88 if (phdr->p_vaddr < min_vaddr)
89 min_vaddr = phdr->p_vaddr;
90 if (phdr->p_vaddr + phdr->p_memsz > max_vaddr)
91 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
92 break;
93 case PT_GNU_RELRO:
94 min_relro_vaddr = PAGE_START(phdr->p_vaddr);
95 max_relro_vaddr = phdr->p_vaddr + phdr->p_memsz;
96
97 // As of 2020-11 in libmonochrome.so RELRO is covered by a LOAD segment.
98 // It is not clear whether this property is going to be guaranteed in
99 // the future. Include the RELRO segment as part of the 'load size'.
100 // This way a potential future change in layout of LOAD segments would
101 // not open address space for racy mmap(MAP_FIXED).
102 if (min_relro_vaddr < min_vaddr)
103 min_vaddr = min_relro_vaddr;
104 if (max_vaddr < max_relro_vaddr)
105 max_vaddr = max_relro_vaddr;
106 break;
107 default:
108 break;
109 }
110 }
111
112 // Fill out size and relro information if there was a match.
113 if (is_matching) {
114 int page_size = sysconf(_SC_PAGESIZE);
115 if (page_size != PAGE_SIZE)
116 abort();
117
118 finder->load_size_ = PAGE_END(max_vaddr) - PAGE_START(min_vaddr);
119 finder->relro_size_ =
120 PAGE_END(max_relro_vaddr) - PAGE_START(min_relro_vaddr);
121 finder->relro_start_ = info->dlpi_addr + PAGE_START(min_relro_vaddr);
122
123 return 1;
124 }
125
126 return 0;
127 }
128
129 } // namespace
130
131 // These tests get linked with base_unittests and leave JNI uninitialized. The
132 // tests must not execute any parts relying on initialization with JNI_Onload().
133
134 class LinkerTest : public testing::Test {
135 public:
136 LinkerTest() = default;
137 ~LinkerTest() override = default;
138 };
139
140 // Checks that NativeLibInfo::CreateSharedRelroFd() creates a shared memory
141 // region that is 'sealed' as read-only.
TEST_F(LinkerTest,CreatedRegionIsSealed)142 TEST_F(LinkerTest, CreatedRegionIsSealed) {
143 if (!NativeLibInfo::SharedMemoryFunctionsSupportedForTesting()) {
144 // The Linker uses functions from libandroid.so that are not available
145 // on Android releases before O. Disable unittests for old releases.
146 return;
147 }
148
149 // Fill a synthetic RELRO region with 0xEE in private anonynous memory.
150 constexpr size_t kRelroSize = 1 << 21; // 2 MiB.
151 void* relro_address = mmap(nullptr, kRelroSize, PROT_READ | PROT_WRITE,
152 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
153 ASSERT_NE(MAP_FAILED, relro_address);
154 NativeLibInfo lib_info = {0, 0};
155 lib_info.set_relro_info_for_testing(
156 reinterpret_cast<uintptr_t>(relro_address), kRelroSize);
157 memset(relro_address, 0xEE, kRelroSize);
158
159 // Create shared RELRO.
160 ASSERT_EQ(true, lib_info.CreateSharedRelroFdForTesting());
161 int relro_fd = lib_info.get_relro_fd_for_testing();
162 ASSERT_NE(-1, relro_fd);
163 base::ScopedFD scoped_fd(relro_fd);
164
165 // Check that a read-only mapping contains the data originally filled in.
166 void* ro_address =
167 mmap(nullptr, kRelroSize, PROT_READ, MAP_SHARED, relro_fd, 0);
168 ASSERT_NE(MAP_FAILED, ro_address);
169 EXPECT_EQ(0xEEEEEEEEU, *reinterpret_cast<uint32_t*>(ro_address));
170 int not_equal = memcmp(relro_address, ro_address, kRelroSize);
171 EXPECT_EQ(0, not_equal);
172 munmap(ro_address, kRelroSize);
173
174 // Check that attempts to mmap with PROT_WRITE fail.
175 EXPECT_EQ(MAP_FAILED, mmap(nullptr, kRelroSize, PROT_READ | PROT_WRITE,
176 MAP_SHARED, relro_fd, 0));
177 EXPECT_EQ(MAP_FAILED, mmap(nullptr, kRelroSize, PROT_READ | PROT_WRITE,
178 MAP_PRIVATE, relro_fd, 0));
179 EXPECT_EQ(MAP_FAILED,
180 mmap(nullptr, kRelroSize, PROT_WRITE, MAP_SHARED, relro_fd, 0));
181 EXPECT_EQ(MAP_FAILED,
182 mmap(nullptr, kRelroSize, PROT_WRITE, MAP_PRIVATE, relro_fd, 0));
183 }
184
TEST_F(LinkerTest,FindReservedMemoryRegion)185 TEST_F(LinkerTest, FindReservedMemoryRegion) {
186 size_t address, size;
187
188 // Find the existing reservation in the current process. The unittest runner
189 // is forked from the system zygote. The reservation should be found when
190 // running on recent Android releases, where it is made by the
191 // reserveAddressSpaceInZygote().
192 bool found_reservation = FindWebViewReservation(&address, &size);
193
194 if (found_reservation) {
195 // Check that the size is at least the minimum reserved by Android, as of
196 // 2021-04.
197 EXPECT_LE(130U * 1024 * 1024, size);
198 return;
199 }
200
201 // TODO(crbug.com/1223747): Check that only non-low-end Android Q+ devices
202 // reach this point.
203
204 // Create a properly named synthetic region with a size smaller than a real
205 // library would need, but still aligned well.
206 static const size_t kSize = 19U * 1024 * 1024;
207 void* synthetic_region_start =
208 mmap(nullptr, kSize, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
209 ASSERT_NE(MAP_FAILED, synthetic_region_start);
210 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, synthetic_region_start, kSize,
211 "[anon:libwebview reservation]");
212
213 // Now the region must be found.
214 EXPECT_TRUE(FindWebViewReservation(&address, &size));
215 EXPECT_EQ(kSize, size);
216 EXPECT_EQ(reinterpret_cast<void*>(address), synthetic_region_start);
217 munmap(synthetic_region_start, kSize);
218 }
219
TEST_F(LinkerTest,FindLibraryRanges)220 TEST_F(LinkerTest, FindLibraryRanges) {
221 static int var_inside = 3;
222
223 NativeLibInfo lib_info = {0, 0};
224 uintptr_t executable_start = reinterpret_cast<uintptr_t>(&__executable_start);
225 lib_info.set_load_address(executable_start);
226
227 EXPECT_TRUE(lib_info.FindRelroAndLibraryRangesInElfForTesting());
228 EXPECT_EQ(executable_start, lib_info.load_address());
229
230 uintptr_t inside_library = reinterpret_cast<uintptr_t>(&var_inside);
231 EXPECT_LE(executable_start, inside_library);
232 EXPECT_LE(inside_library,
233 lib_info.load_address() + lib_info.get_load_size_for_testing());
234
235 EXPECT_LE(lib_info.load_address(), lib_info.get_relro_start_for_testing());
236 EXPECT_LE(lib_info.get_relro_start_for_testing(),
237 lib_info.load_address() + lib_info.get_load_size_for_testing());
238 }
239
TEST_F(LinkerTest,FindLibraryRangesWhenLoadAddressWasReset)240 TEST_F(LinkerTest, FindLibraryRangesWhenLoadAddressWasReset) {
241 NativeLibInfo other_lib_info = {0, 0};
242 uintptr_t executable_start = reinterpret_cast<uintptr_t>(&__executable_start);
243 other_lib_info.set_load_address(executable_start);
244 other_lib_info.set_relro_fd_for_testing(123);
245 NativeLibInfo lib_info = {0, 0};
246 EXPECT_FALSE(lib_info.CompareRelroAndReplaceItBy(other_lib_info));
247 }
248
249 // Check that discovering RELRO segment address ranges and the DSO ranges agrees
250 // with the method based on dl_iterate_phdr(3). The check is performed on the
251 // test library, not on libmonochrome.
TEST_F(LinkerTest,LibraryRangesViaIteratePhdr)252 TEST_F(LinkerTest, LibraryRangesViaIteratePhdr) {
253 // Find the ranges using dl_iterate_phdr().
254 if (!dl_iterate_phdr) {
255 ASSERT_TRUE(false) << "dl_iterate_phdr() not found";
256 }
257 uintptr_t executable_start = reinterpret_cast<uintptr_t>(&__executable_start);
258 LibraryRangeFinder finder(executable_start);
259 ASSERT_EQ(1, dl_iterate_phdr(&LibraryRangeFinder::VisitLibraryPhdrs,
260 reinterpret_cast<void*>(&finder)));
261 ASSERT_LE(finder.relro_start() + finder.relro_size(),
262 finder.load_address() + finder.load_size());
263
264 // Find the ranges by parsing ELF.
265 NativeLibInfo lib_info2 = {0, 0};
266 lib_info2.set_load_address(executable_start);
267 EXPECT_TRUE(lib_info2.FindRelroAndLibraryRangesInElfForTesting());
268
269 // Compare results.
270 EXPECT_EQ(finder.load_address(), lib_info2.load_address());
271 EXPECT_EQ(finder.load_size(), lib_info2.get_load_size_for_testing());
272 EXPECT_EQ(finder.relro_start(), lib_info2.get_relro_start_for_testing());
273 }
274
275 } // namespace chromium_android_linker
276