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