blob: 865a7d4cfd55304fb4be4a678e4cabaf867a0b0b [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.
Nicolas Geoffray349845a2019-06-19 13:13:10 +010026#include "base/membarrier.h"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010027#include "base/memfd.h"
28#include "base/systrace.h"
29#include "gc/allocator/dlmalloc.h"
30#include "jit/jit_scoped_code_cache_write.h"
31#include "oat_quick_method_header.h"
Nicolas Geoffray2411f492019-06-14 08:54:46 +010032#include "palette/palette.h"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010033
34using android::base::unique_fd;
35
36namespace art {
37namespace jit {
38
39// Data cache will be half of the capacity
40// Code cache will be the other half of the capacity.
41// TODO: Make this variable?
42static constexpr size_t kCodeAndDataCapacityDivider = 2;
43
Nicolas Geoffray9c54e182019-06-18 10:42:52 +010044bool JitMemoryRegion::Initialize(size_t initial_capacity,
45 size_t max_capacity,
46 bool rwx_memory_allowed,
47 bool is_zygote,
48 std::string* error_msg) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010049 ScopedTrace trace(__PRETTY_FUNCTION__);
50
Nicolas Geoffray9c54e182019-06-18 10:42:52 +010051 CHECK_GE(max_capacity, initial_capacity);
52 CHECK(max_capacity <= 1 * GB) << "The max supported size for JIT code cache is 1GB";
53 // Align both capacities to page size, as that's the unit mspaces use.
54 initial_capacity_ = RoundDown(initial_capacity, 2 * kPageSize);
55 max_capacity_ = RoundDown(max_capacity, 2 * kPageSize);
56 current_capacity_ = initial_capacity,
57 data_end_ = initial_capacity / kCodeAndDataCapacityDivider;
58 exec_end_ = initial_capacity - data_end_;
59
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010060 const size_t capacity = max_capacity_;
61 const size_t data_capacity = capacity / kCodeAndDataCapacityDivider;
62 const size_t exec_capacity = capacity - data_capacity;
63
64 // File descriptor enabling dual-view mapping of code section.
65 unique_fd mem_fd;
66
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +000067 if (is_zygote) {
68 // Because we are not going to GC code generated by the zygote, just use all available.
69 current_capacity_ = max_capacity;
70 mem_fd = unique_fd(CreateZygoteMemory(capacity, error_msg));
71 if (mem_fd.get() < 0) {
72 return false;
73 }
74 } else {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010075 // Bionic supports memfd_create, but the call may fail on older kernels.
76 mem_fd = unique_fd(art::memfd_create("/jit-cache", /* flags= */ 0));
77 if (mem_fd.get() < 0) {
78 std::ostringstream oss;
79 oss << "Failed to initialize dual view JIT. memfd_create() error: " << strerror(errno);
80 if (!rwx_memory_allowed) {
81 // Without using RWX page permissions, the JIT can not fallback to single mapping as it
82 // requires tranitioning the code pages to RWX for updates.
83 *error_msg = oss.str();
84 return false;
85 }
86 VLOG(jit) << oss.str();
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +000087 } else if (ftruncate(mem_fd, capacity) != 0) {
88 std::ostringstream oss;
89 oss << "Failed to initialize memory file: " << strerror(errno);
90 *error_msg = oss.str();
91 return false;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010092 }
93 }
94
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010095 std::string data_cache_name = is_zygote ? "zygote-data-code-cache" : "data-code-cache";
96 std::string exec_cache_name = is_zygote ? "zygote-jit-code-cache" : "jit-code-cache";
97
98 std::string error_str;
99 // Map name specific for android_os_Debug.cpp accounting.
100 // Map in low 4gb to simplify accessing root tables for x86_64.
101 // We could do PC-relative addressing to avoid this problem, but that
102 // would require reserving code and data area before submitting, which
103 // means more windows for the code memory to be RWX.
104 int base_flags;
105 MemMap data_pages;
106 if (mem_fd.get() >= 0) {
107 // Dual view of JIT code cache case. Create an initial mapping of data pages large enough
108 // for data and non-writable view of JIT code pages. We use the memory file descriptor to
109 // enable dual mapping - we'll create a second mapping using the descriptor below. The
110 // mappings will look like:
111 //
112 // VA PA
113 //
114 // +---------------+
115 // | non exec code |\
116 // +---------------+ \
117 // : :\ \
118 // +---------------+.\.+---------------+
119 // | exec code | \| code |
120 // +---------------+...+---------------+
121 // | data | | data |
122 // +---------------+...+---------------+
123 //
124 // In this configuration code updates are written to the non-executable view of the code
125 // cache, and the executable view of the code cache has fixed RX memory protections.
126 //
127 // This memory needs to be mapped shared as the code portions will have two mappings.
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100128 //
129 // Additionally, the zyzote will create a dual view of the data portion of
130 // the cache. This mapping will be read-only, whereas the second mapping
131 // will be writable.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100132 base_flags = MAP_SHARED;
133 data_pages = MemMap::MapFile(
134 data_capacity + exec_capacity,
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100135 is_zygote ? kProtR : kProtRW,
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100136 base_flags,
137 mem_fd,
138 /* start= */ 0,
139 /* low_4gb= */ true,
140 data_cache_name.c_str(),
141 &error_str);
142 } else {
143 // Single view of JIT code cache case. Create an initial mapping of data pages large enough
144 // for data and JIT code pages. The mappings will look like:
145 //
146 // VA PA
147 //
148 // +---------------+...+---------------+
149 // | exec code | | code |
150 // +---------------+...+---------------+
151 // | data | | data |
152 // +---------------+...+---------------+
153 //
154 // In this configuration code updates are written to the executable view of the code cache,
155 // and the executable view of the code cache transitions RX to RWX for the update and then
156 // back to RX after the update.
157 base_flags = MAP_PRIVATE | MAP_ANON;
158 data_pages = MemMap::MapAnonymous(
159 data_cache_name.c_str(),
160 data_capacity + exec_capacity,
161 kProtRW,
162 /* low_4gb= */ true,
163 &error_str);
164 }
165
166 if (!data_pages.IsValid()) {
167 std::ostringstream oss;
168 oss << "Failed to create read write cache: " << error_str << " size=" << capacity;
169 *error_msg = oss.str();
170 return false;
171 }
172
173 MemMap exec_pages;
174 MemMap non_exec_pages;
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100175 MemMap writable_data_pages;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100176 if (exec_capacity > 0) {
177 uint8_t* const divider = data_pages.Begin() + data_capacity;
178 // Set initial permission for executable view to catch any SELinux permission problems early
179 // (for processes that cannot map WX pages). Otherwise, this region does not need to be
180 // executable as there is no code in the cache yet.
181 exec_pages = data_pages.RemapAtEnd(divider,
182 exec_cache_name.c_str(),
183 kProtRX,
184 base_flags | MAP_FIXED,
185 mem_fd.get(),
186 (mem_fd.get() >= 0) ? data_capacity : 0,
187 &error_str);
188 if (!exec_pages.IsValid()) {
189 std::ostringstream oss;
190 oss << "Failed to create read execute code cache: " << error_str << " size=" << capacity;
191 *error_msg = oss.str();
192 return false;
193 }
194
195 if (mem_fd.get() >= 0) {
196 // For dual view, create the secondary view of code memory used for updating code. This view
197 // is never executable.
198 std::string name = exec_cache_name + "-rw";
199 non_exec_pages = MemMap::MapFile(exec_capacity,
200 kProtR,
201 base_flags,
202 mem_fd,
203 /* start= */ data_capacity,
204 /* low_4GB= */ false,
205 name.c_str(),
206 &error_str);
207 if (!non_exec_pages.IsValid()) {
208 static const char* kFailedNxView = "Failed to map non-executable view of JIT code cache";
209 if (rwx_memory_allowed) {
210 // Log and continue as single view JIT (requires RWX memory).
211 VLOG(jit) << kFailedNxView;
212 } else {
213 *error_msg = kFailedNxView;
214 return false;
215 }
216 }
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100217 // For the zygote, create a dual view of the data cache.
218 if (is_zygote) {
219 name = data_cache_name + "-rw";
220 writable_data_pages = MemMap::MapFile(data_capacity,
221 kProtRW,
222 base_flags,
223 mem_fd,
224 /* start= */ 0,
225 /* low_4GB= */ false,
226 name.c_str(),
227 &error_str);
228 if (!writable_data_pages.IsValid()) {
229 std::ostringstream oss;
230 oss << "Failed to create dual data view for zygote: " << error_str;
231 *error_msg = oss.str();
232 return false;
233 }
234 // Now that we have created the writable and executable mappings, prevent creating any new
235 // ones.
236 if (!ProtectZygoteMemory(mem_fd.get(), error_msg)) {
237 return false;
238 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000239 }
240 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100241 } else {
242 // Profiling only. No memory for code required.
243 }
244
245 data_pages_ = std::move(data_pages);
246 exec_pages_ = std::move(exec_pages);
247 non_exec_pages_ = std::move(non_exec_pages);
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100248 writable_data_pages_ = std::move(writable_data_pages);
249
250 VLOG(jit) << "Created JitMemoryRegion"
251 << ": data_pages=" << reinterpret_cast<void*>(data_pages_.Begin())
252 << ", exec_pages=" << reinterpret_cast<void*>(exec_pages_.Begin())
253 << ", non_exec_pages=" << reinterpret_cast<void*>(non_exec_pages_.Begin())
254 << ", writable_data_pages=" << reinterpret_cast<void*>(writable_data_pages_.Begin());
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100255
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100256 // Now that the pages are initialized, initialize the spaces.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100257
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100258 // Initialize the data heap.
259 data_mspace_ = create_mspace_with_base(
260 HasDualDataMapping() ? writable_data_pages_.Begin() : data_pages_.Begin(),
261 data_end_,
262 /* locked= */ false);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100263 CHECK(data_mspace_ != nullptr) << "create_mspace_with_base (data) failed";
264
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100265 // Initialize the code heap.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100266 MemMap* code_heap = nullptr;
267 if (non_exec_pages_.IsValid()) {
268 code_heap = &non_exec_pages_;
269 } else if (exec_pages_.IsValid()) {
270 code_heap = &exec_pages_;
271 }
272 if (code_heap != nullptr) {
273 // Make all pages reserved for the code heap writable. The mspace allocator, that manages the
274 // heap, will take and initialize pages in create_mspace_with_base().
275 CheckedCall(mprotect, "create code heap", code_heap->Begin(), code_heap->Size(), kProtRW);
276 exec_mspace_ = create_mspace_with_base(code_heap->Begin(), exec_end_, false /*locked*/);
277 CHECK(exec_mspace_ != nullptr) << "create_mspace_with_base (exec) failed";
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000278 SetFootprintLimit(current_capacity_);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100279 // Protect pages containing heap metadata. Updates to the code heap toggle write permission to
280 // perform the update and there are no other times write access is required.
281 CheckedCall(mprotect, "protect code heap", code_heap->Begin(), code_heap->Size(), kProtR);
282 } else {
283 exec_mspace_ = nullptr;
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000284 SetFootprintLimit(current_capacity_);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100285 }
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100286 return true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100287}
288
289void JitMemoryRegion::SetFootprintLimit(size_t new_footprint) {
290 size_t data_space_footprint = new_footprint / kCodeAndDataCapacityDivider;
291 DCHECK(IsAlignedParam(data_space_footprint, kPageSize));
292 DCHECK_EQ(data_space_footprint * kCodeAndDataCapacityDivider, new_footprint);
293 mspace_set_footprint_limit(data_mspace_, data_space_footprint);
294 if (HasCodeMapping()) {
295 ScopedCodeCacheWrite scc(*this);
296 mspace_set_footprint_limit(exec_mspace_, new_footprint - data_space_footprint);
297 }
298}
299
300bool JitMemoryRegion::IncreaseCodeCacheCapacity() {
301 if (current_capacity_ == max_capacity_) {
302 return false;
303 }
304
305 // Double the capacity if we're below 1MB, or increase it by 1MB if
306 // we're above.
307 if (current_capacity_ < 1 * MB) {
308 current_capacity_ *= 2;
309 } else {
310 current_capacity_ += 1 * MB;
311 }
312 if (current_capacity_ > max_capacity_) {
313 current_capacity_ = max_capacity_;
314 }
315
316 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
317
318 SetFootprintLimit(current_capacity_);
319
320 return true;
321}
322
323// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
324// is already held.
325void* JitMemoryRegion::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
326 if (mspace == exec_mspace_) {
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100327 CHECK(exec_mspace_ != nullptr);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100328 const MemMap* const code_pages = GetUpdatableCodeMapping();
329 void* result = code_pages->Begin() + exec_end_;
330 exec_end_ += increment;
331 return result;
332 } else {
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100333 CHECK_EQ(data_mspace_, mspace);
334 const MemMap* const writable_data_pages = GetWritableDataMapping();
335 void* result = writable_data_pages->Begin() + data_end_;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100336 data_end_ += increment;
337 return result;
338 }
339}
340
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100341const uint8_t* JitMemoryRegion::AllocateCode(const uint8_t* code,
342 size_t code_size,
343 const uint8_t* stack_map,
344 bool has_should_deoptimize_flag) {
345 ScopedCodeCacheWrite scc(*this);
346
Orion Hodsone764f382019-06-27 12:56:48 +0100347 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100348 // Ensure the header ends up at expected instruction alignment.
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100349 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
350 size_t total_size = header_size + code_size;
351
352 // Each allocation should be on its own set of cache lines.
353 // `total_size` covers the OatQuickMethodHeader, the JIT generated machine code,
354 // and any alignment padding.
355 DCHECK_GT(total_size, header_size);
356 uint8_t* w_memory = reinterpret_cast<uint8_t*>(
357 mspace_memalign(exec_mspace_, alignment, total_size));
358 if (w_memory == nullptr) {
359 return nullptr;
360 }
361 uint8_t* x_memory = GetExecutableAddress(w_memory);
362 // Ensure the header ends up at expected instruction alignment.
363 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(w_memory + header_size), alignment);
364 used_memory_for_code_ += mspace_usable_size(w_memory);
365 const uint8_t* result = x_memory + header_size;
366
367 // Write the code.
368 std::copy(code, code + code_size, w_memory + header_size);
369
370 // Write the header.
371 OatQuickMethodHeader* method_header =
372 OatQuickMethodHeader::FromCodePointer(w_memory + header_size);
373 new (method_header) OatQuickMethodHeader(
374 (stack_map != nullptr) ? result - stack_map : 0u,
375 code_size);
376 if (has_should_deoptimize_flag) {
377 method_header->SetHasShouldDeoptimizeFlag();
378 }
379
380 // Both instruction and data caches need flushing to the point of unification where both share
381 // a common view of memory. Flushing the data cache ensures the dirty cachelines from the
382 // newly added code are written out to the point of unification. Flushing the instruction
383 // cache ensures the newly written code will be fetched from the point of unification before
384 // use. Memory in the code cache is re-cycled as code is added and removed. The flushes
385 // prevent stale code from residing in the instruction cache.
386 //
387 // Caches are flushed before write permission is removed because some ARMv8 Qualcomm kernels
388 // may trigger a segfault if a page fault occurs when requesting a cache maintenance
389 // operation. This is a kernel bug that we need to work around until affected devices
390 // (e.g. Nexus 5X and 6P) stop being supported or their kernels are fixed.
391 //
392 // For reference, this behavior is caused by this commit:
393 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
394 //
Orion Hodsonaeb02232019-06-25 14:18:18 +0100395 bool cache_flush_success = true;
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100396 if (HasDualCodeMapping()) {
Orion Hodsonaeb02232019-06-25 14:18:18 +0100397 // Flush d-cache for the non-executable mapping.
398 cache_flush_success = FlushCpuCaches(w_memory, w_memory + total_size);
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100399 }
400
Orion Hodsonaeb02232019-06-25 14:18:18 +0100401 // Invalidate i-cache for the executable mapping.
402 if (cache_flush_success) {
403 cache_flush_success = FlushCpuCaches(x_memory, x_memory + total_size);
404 }
405
406 // If flushing the cache has failed, reject the allocation because we can't guarantee
407 // correctness of the instructions present in the processor caches.
408 if (!cache_flush_success) {
409 PLOG(ERROR) << "Cache flush failed triggering code allocation failure";
410 FreeCode(x_memory);
411 return nullptr;
412 }
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100413
414 // Ensure CPU instruction pipelines are flushed for all cores. This is necessary for
415 // correctness as code may still be in instruction pipelines despite the i-cache flush. It is
416 // not safe to assume that changing permissions with mprotect (RX->RWX->RX) will cause a TLB
417 // shootdown (incidentally invalidating the CPU pipelines by sending an IPI to all cores to
418 // notify them of the TLB invalidation). Some architectures, notably ARM and ARM64, have
419 // hardware support that broadcasts TLB invalidations and so their kernels have no software
420 // based TLB shootdown. The sync-core flavor of membarrier was introduced in Linux 4.16 to
421 // address this (see mbarrier(2)). The membarrier here will fail on prior kernels and on
422 // platforms lacking the appropriate support.
423 art::membarrier(art::MembarrierCommand::kPrivateExpeditedSyncCore);
424
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100425 return result;
426}
427
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100428static void FillRootTable(uint8_t* roots_data, const std::vector<Handle<mirror::Object>>& roots)
429 REQUIRES(Locks::jit_lock_)
430 REQUIRES_SHARED(Locks::mutator_lock_) {
431 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
432 const uint32_t length = roots.size();
433 // Put all roots in `roots_data`.
434 for (uint32_t i = 0; i < length; ++i) {
435 ObjPtr<mirror::Object> object = roots[i].Get();
436 gc_roots[i] = GcRoot<mirror::Object>(object);
437 }
438 // Store the length of the table at the end. This will allow fetching it from a stack_map
439 // pointer.
440 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
441}
442
Orion Hodsonaeb02232019-06-25 14:18:18 +0100443bool JitMemoryRegion::CommitData(uint8_t* roots_data,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100444 const std::vector<Handle<mirror::Object>>& roots,
445 const uint8_t* stack_map,
446 size_t stack_map_size) {
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100447 roots_data = GetWritableDataAddress(roots_data);
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100448 size_t root_table_size = ComputeRootTableSize(roots.size());
449 uint8_t* stack_map_data = roots_data + root_table_size;
450 FillRootTable(roots_data, roots);
451 memcpy(stack_map_data, stack_map, stack_map_size);
452 // Flush data cache, as compiled code references literals in it.
Orion Hodsonaeb02232019-06-25 14:18:18 +0100453 // TODO(oth): establish whether this is necessary.
454 if (UNLIKELY(!FlushCpuCaches(roots_data, roots_data + root_table_size + stack_map_size))) {
455 VLOG(jit) << "Failed to flush data in CommitData";
456 return false;
457 }
458 return true;
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100459}
460
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100461void JitMemoryRegion::FreeCode(const uint8_t* code) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100462 code = GetNonExecutableAddress(code);
463 used_memory_for_code_ -= mspace_usable_size(code);
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100464 mspace_free(exec_mspace_, const_cast<uint8_t*>(code));
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100465}
466
467uint8_t* JitMemoryRegion::AllocateData(size_t data_size) {
468 void* result = mspace_malloc(data_mspace_, data_size);
469 used_memory_for_data_ += mspace_usable_size(result);
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100470 return reinterpret_cast<uint8_t*>(GetNonWritableDataAddress(result));
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100471}
472
473void JitMemoryRegion::FreeData(uint8_t* data) {
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100474 data = GetWritableDataAddress(data);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100475 used_memory_for_data_ -= mspace_usable_size(data);
476 mspace_free(data_mspace_, data);
477}
478
Nicolas Geoffray2411f492019-06-14 08:54:46 +0100479#if defined(__BIONIC__)
480
481static bool IsSealFutureWriteSupportedInternal() {
482 unique_fd fd(art::memfd_create("test_android_memfd", MFD_ALLOW_SEALING));
483 if (fd == -1) {
484 LOG(INFO) << "memfd_create failed: " << strerror(errno) << ", no memfd support.";
485 return false;
486 }
487
488 if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
489 LOG(INFO) << "fcntl(F_ADD_SEALS) failed: " << strerror(errno) << ", no memfd support.";
490 return false;
491 }
492
493 LOG(INFO) << "Using memfd for future sealing";
494 return true;
495}
496
497static bool IsSealFutureWriteSupported() {
498 static bool is_seal_future_write_supported = IsSealFutureWriteSupportedInternal();
499 return is_seal_future_write_supported;
500}
501
502int JitMemoryRegion::CreateZygoteMemory(size_t capacity, std::string* error_msg) {
503 /* Check if kernel support exists, otherwise fall back to ashmem */
504 static const char* kRegionName = "/jit-zygote-cache";
505 if (IsSealFutureWriteSupported()) {
506 int fd = art::memfd_create(kRegionName, MFD_ALLOW_SEALING);
507 if (fd == -1) {
508 std::ostringstream oss;
509 oss << "Failed to create zygote mapping: " << strerror(errno);
510 *error_msg = oss.str();
511 return -1;
512 }
513
514 if (ftruncate(fd, capacity) != 0) {
515 std::ostringstream oss;
516 oss << "Failed to create zygote mapping: " << strerror(errno);
517 *error_msg = oss.str();
518 return -1;
519 }
520
521 return fd;
522 }
523
524 LOG(INFO) << "Falling back to ashmem implementation for JIT zygote mapping";
525
526 int fd;
527 PaletteStatus status = PaletteAshmemCreateRegion(kRegionName, capacity, &fd);
528 if (status != PaletteStatus::kOkay) {
529 CHECK_EQ(status, PaletteStatus::kCheckErrno);
530 std::ostringstream oss;
531 oss << "Failed to create zygote mapping: " << strerror(errno);
532 *error_msg = oss.str();
533 return -1;
534 }
535 return fd;
536}
537
538bool JitMemoryRegion::ProtectZygoteMemory(int fd, std::string* error_msg) {
539 if (IsSealFutureWriteSupported()) {
540 if (fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL | F_SEAL_FUTURE_WRITE)
541 == -1) {
542 std::ostringstream oss;
543 oss << "Failed to protect zygote mapping: " << strerror(errno);
544 *error_msg = oss.str();
545 return false;
546 }
547 } else {
548 PaletteStatus status = PaletteAshmemSetProtRegion(fd, PROT_READ);
549 if (status != PaletteStatus::kOkay) {
550 CHECK_EQ(status, PaletteStatus::kCheckErrno);
551 std::ostringstream oss;
552 oss << "Failed to protect zygote mapping: " << strerror(errno);
553 *error_msg = oss.str();
554 return false;
555 }
556 }
557 return true;
558}
559
560#else
561
562// When running on non-bionic configuration, this is not supported.
563int JitMemoryRegion::CreateZygoteMemory(size_t capacity ATTRIBUTE_UNUSED,
564 std::string* error_msg ATTRIBUTE_UNUSED) {
565 return -1;
566}
567
568bool JitMemoryRegion::ProtectZygoteMemory(int fd ATTRIBUTE_UNUSED,
569 std::string* error_msg ATTRIBUTE_UNUSED) {
570 return true;
571}
572
573#endif
574
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100575} // namespace jit
576} // namespace art