blob: 3c08ff6d64b1946fe8056a07188b7faa60c4f407 [file] [log] [blame]
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001/*
2 * Copyright 2019 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 "jit_memory_region.h"
18
Nicolas Geoffray2411f492019-06-14 08:54:46 +010019#include <fcntl.h>
20#include <unistd.h>
21
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010022#include <android-base/unique_fd.h>
23#include "base/bit_utils.h" // For RoundDown, RoundUp
24#include "base/globals.h"
25#include "base/logging.h" // For VLOG.
26#include "base/memfd.h"
27#include "base/systrace.h"
28#include "gc/allocator/dlmalloc.h"
29#include "jit/jit_scoped_code_cache_write.h"
30#include "oat_quick_method_header.h"
Nicolas Geoffray2411f492019-06-14 08:54:46 +010031#include "palette/palette.h"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010032
33using android::base::unique_fd;
34
35namespace art {
36namespace jit {
37
38// Data cache will be half of the capacity
39// Code cache will be the other half of the capacity.
40// TODO: Make this variable?
41static constexpr size_t kCodeAndDataCapacityDivider = 2;
42
43bool JitMemoryRegion::InitializeMappings(bool rwx_memory_allowed,
44 bool is_zygote,
45 std::string* error_msg) {
46 ScopedTrace trace(__PRETTY_FUNCTION__);
47
48 const size_t capacity = max_capacity_;
49 const size_t data_capacity = capacity / kCodeAndDataCapacityDivider;
50 const size_t exec_capacity = capacity - data_capacity;
51
52 // File descriptor enabling dual-view mapping of code section.
53 unique_fd mem_fd;
54
55 // Zygote shouldn't create a shared mapping for JIT, so we cannot use dual view
56 // for it.
57 if (!is_zygote) {
58 // Bionic supports memfd_create, but the call may fail on older kernels.
59 mem_fd = unique_fd(art::memfd_create("/jit-cache", /* flags= */ 0));
60 if (mem_fd.get() < 0) {
61 std::ostringstream oss;
62 oss << "Failed to initialize dual view JIT. memfd_create() error: " << strerror(errno);
63 if (!rwx_memory_allowed) {
64 // Without using RWX page permissions, the JIT can not fallback to single mapping as it
65 // requires tranitioning the code pages to RWX for updates.
66 *error_msg = oss.str();
67 return false;
68 }
69 VLOG(jit) << oss.str();
70 }
71 }
72
73 if (mem_fd.get() >= 0 && ftruncate(mem_fd, capacity) != 0) {
74 std::ostringstream oss;
75 oss << "Failed to initialize memory file: " << strerror(errno);
76 *error_msg = oss.str();
77 return false;
78 }
79
80 std::string data_cache_name = is_zygote ? "zygote-data-code-cache" : "data-code-cache";
81 std::string exec_cache_name = is_zygote ? "zygote-jit-code-cache" : "jit-code-cache";
82
83 std::string error_str;
84 // Map name specific for android_os_Debug.cpp accounting.
85 // Map in low 4gb to simplify accessing root tables for x86_64.
86 // We could do PC-relative addressing to avoid this problem, but that
87 // would require reserving code and data area before submitting, which
88 // means more windows for the code memory to be RWX.
89 int base_flags;
90 MemMap data_pages;
91 if (mem_fd.get() >= 0) {
92 // Dual view of JIT code cache case. Create an initial mapping of data pages large enough
93 // for data and non-writable view of JIT code pages. We use the memory file descriptor to
94 // enable dual mapping - we'll create a second mapping using the descriptor below. The
95 // mappings will look like:
96 //
97 // VA PA
98 //
99 // +---------------+
100 // | non exec code |\
101 // +---------------+ \
102 // : :\ \
103 // +---------------+.\.+---------------+
104 // | exec code | \| code |
105 // +---------------+...+---------------+
106 // | data | | data |
107 // +---------------+...+---------------+
108 //
109 // In this configuration code updates are written to the non-executable view of the code
110 // cache, and the executable view of the code cache has fixed RX memory protections.
111 //
112 // This memory needs to be mapped shared as the code portions will have two mappings.
113 base_flags = MAP_SHARED;
114 data_pages = MemMap::MapFile(
115 data_capacity + exec_capacity,
116 kProtRW,
117 base_flags,
118 mem_fd,
119 /* start= */ 0,
120 /* low_4gb= */ true,
121 data_cache_name.c_str(),
122 &error_str);
123 } else {
124 // Single view of JIT code cache case. Create an initial mapping of data pages large enough
125 // for data and JIT code pages. The mappings will look like:
126 //
127 // VA PA
128 //
129 // +---------------+...+---------------+
130 // | exec code | | code |
131 // +---------------+...+---------------+
132 // | data | | data |
133 // +---------------+...+---------------+
134 //
135 // In this configuration code updates are written to the executable view of the code cache,
136 // and the executable view of the code cache transitions RX to RWX for the update and then
137 // back to RX after the update.
138 base_flags = MAP_PRIVATE | MAP_ANON;
139 data_pages = MemMap::MapAnonymous(
140 data_cache_name.c_str(),
141 data_capacity + exec_capacity,
142 kProtRW,
143 /* low_4gb= */ true,
144 &error_str);
145 }
146
147 if (!data_pages.IsValid()) {
148 std::ostringstream oss;
149 oss << "Failed to create read write cache: " << error_str << " size=" << capacity;
150 *error_msg = oss.str();
151 return false;
152 }
153
154 MemMap exec_pages;
155 MemMap non_exec_pages;
156 if (exec_capacity > 0) {
157 uint8_t* const divider = data_pages.Begin() + data_capacity;
158 // Set initial permission for executable view to catch any SELinux permission problems early
159 // (for processes that cannot map WX pages). Otherwise, this region does not need to be
160 // executable as there is no code in the cache yet.
161 exec_pages = data_pages.RemapAtEnd(divider,
162 exec_cache_name.c_str(),
163 kProtRX,
164 base_flags | MAP_FIXED,
165 mem_fd.get(),
166 (mem_fd.get() >= 0) ? data_capacity : 0,
167 &error_str);
168 if (!exec_pages.IsValid()) {
169 std::ostringstream oss;
170 oss << "Failed to create read execute code cache: " << error_str << " size=" << capacity;
171 *error_msg = oss.str();
172 return false;
173 }
174
175 if (mem_fd.get() >= 0) {
176 // For dual view, create the secondary view of code memory used for updating code. This view
177 // is never executable.
178 std::string name = exec_cache_name + "-rw";
179 non_exec_pages = MemMap::MapFile(exec_capacity,
180 kProtR,
181 base_flags,
182 mem_fd,
183 /* start= */ data_capacity,
184 /* low_4GB= */ false,
185 name.c_str(),
186 &error_str);
187 if (!non_exec_pages.IsValid()) {
188 static const char* kFailedNxView = "Failed to map non-executable view of JIT code cache";
189 if (rwx_memory_allowed) {
190 // Log and continue as single view JIT (requires RWX memory).
191 VLOG(jit) << kFailedNxView;
192 } else {
193 *error_msg = kFailedNxView;
194 return false;
195 }
196 }
197 }
198 } else {
199 // Profiling only. No memory for code required.
200 }
201
202 data_pages_ = std::move(data_pages);
203 exec_pages_ = std::move(exec_pages);
204 non_exec_pages_ = std::move(non_exec_pages);
205 return true;
206}
207
208void JitMemoryRegion::InitializeState(size_t initial_capacity, size_t max_capacity) {
209 CHECK_GE(max_capacity, initial_capacity);
210 CHECK(max_capacity <= 1 * GB) << "The max supported size for JIT code cache is 1GB";
211 // Align both capacities to page size, as that's the unit mspaces use.
212 initial_capacity_ = RoundDown(initial_capacity, 2 * kPageSize);
213 max_capacity_ = RoundDown(max_capacity, 2 * kPageSize);
214 current_capacity_ = initial_capacity,
215 data_end_ = initial_capacity / kCodeAndDataCapacityDivider;
216 exec_end_ = initial_capacity - data_end_;
217}
218
219void JitMemoryRegion::InitializeSpaces() {
220 // Initialize the data heap
221 data_mspace_ = create_mspace_with_base(data_pages_.Begin(), data_end_, false /*locked*/);
222 CHECK(data_mspace_ != nullptr) << "create_mspace_with_base (data) failed";
223
224 // Initialize the code heap
225 MemMap* code_heap = nullptr;
226 if (non_exec_pages_.IsValid()) {
227 code_heap = &non_exec_pages_;
228 } else if (exec_pages_.IsValid()) {
229 code_heap = &exec_pages_;
230 }
231 if (code_heap != nullptr) {
232 // Make all pages reserved for the code heap writable. The mspace allocator, that manages the
233 // heap, will take and initialize pages in create_mspace_with_base().
234 CheckedCall(mprotect, "create code heap", code_heap->Begin(), code_heap->Size(), kProtRW);
235 exec_mspace_ = create_mspace_with_base(code_heap->Begin(), exec_end_, false /*locked*/);
236 CHECK(exec_mspace_ != nullptr) << "create_mspace_with_base (exec) failed";
237 SetFootprintLimit(initial_capacity_);
238 // Protect pages containing heap metadata. Updates to the code heap toggle write permission to
239 // perform the update and there are no other times write access is required.
240 CheckedCall(mprotect, "protect code heap", code_heap->Begin(), code_heap->Size(), kProtR);
241 } else {
242 exec_mspace_ = nullptr;
243 SetFootprintLimit(initial_capacity_);
244 }
245}
246
247void JitMemoryRegion::SetFootprintLimit(size_t new_footprint) {
248 size_t data_space_footprint = new_footprint / kCodeAndDataCapacityDivider;
249 DCHECK(IsAlignedParam(data_space_footprint, kPageSize));
250 DCHECK_EQ(data_space_footprint * kCodeAndDataCapacityDivider, new_footprint);
251 mspace_set_footprint_limit(data_mspace_, data_space_footprint);
252 if (HasCodeMapping()) {
253 ScopedCodeCacheWrite scc(*this);
254 mspace_set_footprint_limit(exec_mspace_, new_footprint - data_space_footprint);
255 }
256}
257
258bool JitMemoryRegion::IncreaseCodeCacheCapacity() {
259 if (current_capacity_ == max_capacity_) {
260 return false;
261 }
262
263 // Double the capacity if we're below 1MB, or increase it by 1MB if
264 // we're above.
265 if (current_capacity_ < 1 * MB) {
266 current_capacity_ *= 2;
267 } else {
268 current_capacity_ += 1 * MB;
269 }
270 if (current_capacity_ > max_capacity_) {
271 current_capacity_ = max_capacity_;
272 }
273
274 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
275
276 SetFootprintLimit(current_capacity_);
277
278 return true;
279}
280
281// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
282// is already held.
283void* JitMemoryRegion::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
284 if (mspace == exec_mspace_) {
285 DCHECK(exec_mspace_ != nullptr);
286 const MemMap* const code_pages = GetUpdatableCodeMapping();
287 void* result = code_pages->Begin() + exec_end_;
288 exec_end_ += increment;
289 return result;
290 } else {
291 DCHECK_EQ(data_mspace_, mspace);
292 void* result = data_pages_.Begin() + data_end_;
293 data_end_ += increment;
294 return result;
295 }
296}
297
298uint8_t* JitMemoryRegion::AllocateCode(size_t code_size) {
299 // Each allocation should be on its own set of cache lines.
300 // `code_size` covers the OatQuickMethodHeader, the JIT generated machine code,
301 // and any alignment padding.
302 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
303 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
304 DCHECK_GT(code_size, header_size);
305 uint8_t* result = reinterpret_cast<uint8_t*>(
306 mspace_memalign(exec_mspace_, kJitCodeAlignment, code_size));
307 // Ensure the header ends up at expected instruction alignment.
308 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
309 used_memory_for_code_ += mspace_usable_size(result);
310 return result;
311}
312
313void JitMemoryRegion::FreeCode(uint8_t* code) {
314 code = GetNonExecutableAddress(code);
315 used_memory_for_code_ -= mspace_usable_size(code);
316 mspace_free(exec_mspace_, code);
317}
318
319uint8_t* JitMemoryRegion::AllocateData(size_t data_size) {
320 void* result = mspace_malloc(data_mspace_, data_size);
321 used_memory_for_data_ += mspace_usable_size(result);
322 return reinterpret_cast<uint8_t*>(result);
323}
324
325void JitMemoryRegion::FreeData(uint8_t* data) {
326 used_memory_for_data_ -= mspace_usable_size(data);
327 mspace_free(data_mspace_, data);
328}
329
Nicolas Geoffray2411f492019-06-14 08:54:46 +0100330#if defined(__BIONIC__)
331
332static bool IsSealFutureWriteSupportedInternal() {
333 unique_fd fd(art::memfd_create("test_android_memfd", MFD_ALLOW_SEALING));
334 if (fd == -1) {
335 LOG(INFO) << "memfd_create failed: " << strerror(errno) << ", no memfd support.";
336 return false;
337 }
338
339 if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
340 LOG(INFO) << "fcntl(F_ADD_SEALS) failed: " << strerror(errno) << ", no memfd support.";
341 return false;
342 }
343
344 LOG(INFO) << "Using memfd for future sealing";
345 return true;
346}
347
348static bool IsSealFutureWriteSupported() {
349 static bool is_seal_future_write_supported = IsSealFutureWriteSupportedInternal();
350 return is_seal_future_write_supported;
351}
352
353int JitMemoryRegion::CreateZygoteMemory(size_t capacity, std::string* error_msg) {
354 /* Check if kernel support exists, otherwise fall back to ashmem */
355 static const char* kRegionName = "/jit-zygote-cache";
356 if (IsSealFutureWriteSupported()) {
357 int fd = art::memfd_create(kRegionName, MFD_ALLOW_SEALING);
358 if (fd == -1) {
359 std::ostringstream oss;
360 oss << "Failed to create zygote mapping: " << strerror(errno);
361 *error_msg = oss.str();
362 return -1;
363 }
364
365 if (ftruncate(fd, capacity) != 0) {
366 std::ostringstream oss;
367 oss << "Failed to create zygote mapping: " << strerror(errno);
368 *error_msg = oss.str();
369 return -1;
370 }
371
372 return fd;
373 }
374
375 LOG(INFO) << "Falling back to ashmem implementation for JIT zygote mapping";
376
377 int fd;
378 PaletteStatus status = PaletteAshmemCreateRegion(kRegionName, capacity, &fd);
379 if (status != PaletteStatus::kOkay) {
380 CHECK_EQ(status, PaletteStatus::kCheckErrno);
381 std::ostringstream oss;
382 oss << "Failed to create zygote mapping: " << strerror(errno);
383 *error_msg = oss.str();
384 return -1;
385 }
386 return fd;
387}
388
389bool JitMemoryRegion::ProtectZygoteMemory(int fd, std::string* error_msg) {
390 if (IsSealFutureWriteSupported()) {
391 if (fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL | F_SEAL_FUTURE_WRITE)
392 == -1) {
393 std::ostringstream oss;
394 oss << "Failed to protect zygote mapping: " << strerror(errno);
395 *error_msg = oss.str();
396 return false;
397 }
398 } else {
399 PaletteStatus status = PaletteAshmemSetProtRegion(fd, PROT_READ);
400 if (status != PaletteStatus::kOkay) {
401 CHECK_EQ(status, PaletteStatus::kCheckErrno);
402 std::ostringstream oss;
403 oss << "Failed to protect zygote mapping: " << strerror(errno);
404 *error_msg = oss.str();
405 return false;
406 }
407 }
408 return true;
409}
410
411#else
412
413// When running on non-bionic configuration, this is not supported.
414int JitMemoryRegion::CreateZygoteMemory(size_t capacity ATTRIBUTE_UNUSED,
415 std::string* error_msg ATTRIBUTE_UNUSED) {
416 return -1;
417}
418
419bool JitMemoryRegion::ProtectZygoteMemory(int fd ATTRIBUTE_UNUSED,
420 std::string* error_msg ATTRIBUTE_UNUSED) {
421 return true;
422}
423
424#endif
425
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100426} // namespace jit
427} // namespace art