blob: b3c2d7e9fe4fac20b843398c272006a454f6d8b3 [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>
Orion Hodsond17eac62019-07-03 17:39:12 +010020#include <sys/utsname.h>
Nicolas Geoffray2411f492019-06-14 08:54:46 +010021#include <unistd.h>
22
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010023#include <android-base/unique_fd.h>
24#include "base/bit_utils.h" // For RoundDown, RoundUp
25#include "base/globals.h"
26#include "base/logging.h" // For VLOG.
Nicolas Geoffray349845a2019-06-19 13:13:10 +010027#include "base/membarrier.h"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010028#include "base/memfd.h"
29#include "base/systrace.h"
30#include "gc/allocator/dlmalloc.h"
31#include "jit/jit_scoped_code_cache_write.h"
32#include "oat_quick_method_header.h"
Nicolas Geoffray2411f492019-06-14 08:54:46 +010033#include "palette/palette.h"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010034
35using android::base::unique_fd;
36
37namespace art {
38namespace jit {
39
40// Data cache will be half of the capacity
41// Code cache will be the other half of the capacity.
42// TODO: Make this variable?
43static constexpr size_t kCodeAndDataCapacityDivider = 2;
44
Nicolas Geoffray9c54e182019-06-18 10:42:52 +010045bool JitMemoryRegion::Initialize(size_t initial_capacity,
46 size_t max_capacity,
47 bool rwx_memory_allowed,
48 bool is_zygote,
49 std::string* error_msg) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010050 ScopedTrace trace(__PRETTY_FUNCTION__);
51
Nicolas Geoffray9c54e182019-06-18 10:42:52 +010052 CHECK_GE(max_capacity, initial_capacity);
53 CHECK(max_capacity <= 1 * GB) << "The max supported size for JIT code cache is 1GB";
54 // Align both capacities to page size, as that's the unit mspaces use.
55 initial_capacity_ = RoundDown(initial_capacity, 2 * kPageSize);
56 max_capacity_ = RoundDown(max_capacity, 2 * kPageSize);
57 current_capacity_ = initial_capacity,
58 data_end_ = initial_capacity / kCodeAndDataCapacityDivider;
59 exec_end_ = initial_capacity - data_end_;
60
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010061 const size_t capacity = max_capacity_;
62 const size_t data_capacity = capacity / kCodeAndDataCapacityDivider;
63 const size_t exec_capacity = capacity - data_capacity;
64
65 // File descriptor enabling dual-view mapping of code section.
66 unique_fd mem_fd;
67
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +000068 if (is_zygote) {
69 // Because we are not going to GC code generated by the zygote, just use all available.
70 current_capacity_ = max_capacity;
71 mem_fd = unique_fd(CreateZygoteMemory(capacity, error_msg));
72 if (mem_fd.get() < 0) {
73 return false;
74 }
75 } else {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010076 // Bionic supports memfd_create, but the call may fail on older kernels.
77 mem_fd = unique_fd(art::memfd_create("/jit-cache", /* flags= */ 0));
78 if (mem_fd.get() < 0) {
79 std::ostringstream oss;
80 oss << "Failed to initialize dual view JIT. memfd_create() error: " << strerror(errno);
81 if (!rwx_memory_allowed) {
82 // Without using RWX page permissions, the JIT can not fallback to single mapping as it
83 // requires tranitioning the code pages to RWX for updates.
84 *error_msg = oss.str();
85 return false;
86 }
87 VLOG(jit) << oss.str();
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +000088 } else if (ftruncate(mem_fd, capacity) != 0) {
89 std::ostringstream oss;
90 oss << "Failed to initialize memory file: " << strerror(errno);
91 *error_msg = oss.str();
92 return false;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010093 }
94 }
95
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010096 std::string data_cache_name = is_zygote ? "zygote-data-code-cache" : "data-code-cache";
97 std::string exec_cache_name = is_zygote ? "zygote-jit-code-cache" : "jit-code-cache";
98
99 std::string error_str;
100 // Map name specific for android_os_Debug.cpp accounting.
101 // Map in low 4gb to simplify accessing root tables for x86_64.
102 // We could do PC-relative addressing to avoid this problem, but that
103 // would require reserving code and data area before submitting, which
104 // means more windows for the code memory to be RWX.
105 int base_flags;
106 MemMap data_pages;
107 if (mem_fd.get() >= 0) {
108 // Dual view of JIT code cache case. Create an initial mapping of data pages large enough
109 // for data and non-writable view of JIT code pages. We use the memory file descriptor to
110 // enable dual mapping - we'll create a second mapping using the descriptor below. The
111 // mappings will look like:
112 //
113 // VA PA
114 //
115 // +---------------+
116 // | non exec code |\
117 // +---------------+ \
118 // : :\ \
119 // +---------------+.\.+---------------+
120 // | exec code | \| code |
121 // +---------------+...+---------------+
122 // | data | | data |
123 // +---------------+...+---------------+
124 //
125 // In this configuration code updates are written to the non-executable view of the code
126 // cache, and the executable view of the code cache has fixed RX memory protections.
127 //
128 // This memory needs to be mapped shared as the code portions will have two mappings.
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100129 //
130 // Additionally, the zyzote will create a dual view of the data portion of
131 // the cache. This mapping will be read-only, whereas the second mapping
132 // will be writable.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100133 base_flags = MAP_SHARED;
134 data_pages = MemMap::MapFile(
135 data_capacity + exec_capacity,
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100136 is_zygote ? kProtR : kProtRW,
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100137 base_flags,
138 mem_fd,
139 /* start= */ 0,
140 /* low_4gb= */ true,
141 data_cache_name.c_str(),
142 &error_str);
143 } else {
144 // Single view of JIT code cache case. Create an initial mapping of data pages large enough
145 // for data and JIT code pages. The mappings will look like:
146 //
147 // VA PA
148 //
149 // +---------------+...+---------------+
150 // | exec code | | code |
151 // +---------------+...+---------------+
152 // | data | | data |
153 // +---------------+...+---------------+
154 //
155 // In this configuration code updates are written to the executable view of the code cache,
156 // and the executable view of the code cache transitions RX to RWX for the update and then
157 // back to RX after the update.
158 base_flags = MAP_PRIVATE | MAP_ANON;
159 data_pages = MemMap::MapAnonymous(
160 data_cache_name.c_str(),
161 data_capacity + exec_capacity,
162 kProtRW,
163 /* low_4gb= */ true,
164 &error_str);
165 }
166
167 if (!data_pages.IsValid()) {
168 std::ostringstream oss;
169 oss << "Failed to create read write cache: " << error_str << " size=" << capacity;
170 *error_msg = oss.str();
171 return false;
172 }
173
174 MemMap exec_pages;
175 MemMap non_exec_pages;
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100176 MemMap writable_data_pages;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100177 if (exec_capacity > 0) {
178 uint8_t* const divider = data_pages.Begin() + data_capacity;
179 // Set initial permission for executable view to catch any SELinux permission problems early
180 // (for processes that cannot map WX pages). Otherwise, this region does not need to be
181 // executable as there is no code in the cache yet.
182 exec_pages = data_pages.RemapAtEnd(divider,
183 exec_cache_name.c_str(),
184 kProtRX,
185 base_flags | MAP_FIXED,
186 mem_fd.get(),
187 (mem_fd.get() >= 0) ? data_capacity : 0,
188 &error_str);
189 if (!exec_pages.IsValid()) {
190 std::ostringstream oss;
191 oss << "Failed to create read execute code cache: " << error_str << " size=" << capacity;
192 *error_msg = oss.str();
193 return false;
194 }
195
196 if (mem_fd.get() >= 0) {
197 // For dual view, create the secondary view of code memory used for updating code. This view
198 // is never executable.
199 std::string name = exec_cache_name + "-rw";
200 non_exec_pages = MemMap::MapFile(exec_capacity,
201 kProtR,
202 base_flags,
203 mem_fd,
204 /* start= */ data_capacity,
205 /* low_4GB= */ false,
206 name.c_str(),
207 &error_str);
208 if (!non_exec_pages.IsValid()) {
209 static const char* kFailedNxView = "Failed to map non-executable view of JIT code cache";
210 if (rwx_memory_allowed) {
211 // Log and continue as single view JIT (requires RWX memory).
212 VLOG(jit) << kFailedNxView;
213 } else {
214 *error_msg = kFailedNxView;
215 return false;
216 }
217 }
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100218 // For the zygote, create a dual view of the data cache.
219 if (is_zygote) {
220 name = data_cache_name + "-rw";
221 writable_data_pages = MemMap::MapFile(data_capacity,
222 kProtRW,
223 base_flags,
224 mem_fd,
225 /* start= */ 0,
226 /* low_4GB= */ false,
227 name.c_str(),
228 &error_str);
229 if (!writable_data_pages.IsValid()) {
230 std::ostringstream oss;
231 oss << "Failed to create dual data view for zygote: " << error_str;
232 *error_msg = oss.str();
233 return false;
234 }
Nicolas Geoffray88f3fd92019-06-27 16:32:13 +0100235 if (writable_data_pages.MadviseDontFork() != 0) {
236 *error_msg = "Failed to madvise dont fork the writable data view";
237 return false;
238 }
239 if (non_exec_pages.MadviseDontFork() != 0) {
240 *error_msg = "Failed to madvise dont fork the writable code view";
241 return false;
242 }
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100243 // Now that we have created the writable and executable mappings, prevent creating any new
244 // ones.
245 if (!ProtectZygoteMemory(mem_fd.get(), error_msg)) {
246 return false;
247 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000248 }
249 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100250 } else {
251 // Profiling only. No memory for code required.
252 }
253
254 data_pages_ = std::move(data_pages);
255 exec_pages_ = std::move(exec_pages);
256 non_exec_pages_ = std::move(non_exec_pages);
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100257 writable_data_pages_ = std::move(writable_data_pages);
258
259 VLOG(jit) << "Created JitMemoryRegion"
260 << ": data_pages=" << reinterpret_cast<void*>(data_pages_.Begin())
261 << ", exec_pages=" << reinterpret_cast<void*>(exec_pages_.Begin())
262 << ", non_exec_pages=" << reinterpret_cast<void*>(non_exec_pages_.Begin())
263 << ", writable_data_pages=" << reinterpret_cast<void*>(writable_data_pages_.Begin());
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100264
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100265 // Now that the pages are initialized, initialize the spaces.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100266
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100267 // Initialize the data heap.
268 data_mspace_ = create_mspace_with_base(
269 HasDualDataMapping() ? writable_data_pages_.Begin() : data_pages_.Begin(),
270 data_end_,
271 /* locked= */ false);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100272 CHECK(data_mspace_ != nullptr) << "create_mspace_with_base (data) failed";
273
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100274 // Initialize the code heap.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100275 MemMap* code_heap = nullptr;
276 if (non_exec_pages_.IsValid()) {
277 code_heap = &non_exec_pages_;
278 } else if (exec_pages_.IsValid()) {
279 code_heap = &exec_pages_;
280 }
281 if (code_heap != nullptr) {
282 // Make all pages reserved for the code heap writable. The mspace allocator, that manages the
283 // heap, will take and initialize pages in create_mspace_with_base().
284 CheckedCall(mprotect, "create code heap", code_heap->Begin(), code_heap->Size(), kProtRW);
285 exec_mspace_ = create_mspace_with_base(code_heap->Begin(), exec_end_, false /*locked*/);
286 CHECK(exec_mspace_ != nullptr) << "create_mspace_with_base (exec) failed";
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000287 SetFootprintLimit(current_capacity_);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100288 // Protect pages containing heap metadata. Updates to the code heap toggle write permission to
289 // perform the update and there are no other times write access is required.
290 CheckedCall(mprotect, "protect code heap", code_heap->Begin(), code_heap->Size(), kProtR);
291 } else {
292 exec_mspace_ = nullptr;
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000293 SetFootprintLimit(current_capacity_);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100294 }
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100295 return true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100296}
297
298void JitMemoryRegion::SetFootprintLimit(size_t new_footprint) {
299 size_t data_space_footprint = new_footprint / kCodeAndDataCapacityDivider;
300 DCHECK(IsAlignedParam(data_space_footprint, kPageSize));
301 DCHECK_EQ(data_space_footprint * kCodeAndDataCapacityDivider, new_footprint);
302 mspace_set_footprint_limit(data_mspace_, data_space_footprint);
303 if (HasCodeMapping()) {
304 ScopedCodeCacheWrite scc(*this);
305 mspace_set_footprint_limit(exec_mspace_, new_footprint - data_space_footprint);
306 }
307}
308
309bool JitMemoryRegion::IncreaseCodeCacheCapacity() {
310 if (current_capacity_ == max_capacity_) {
311 return false;
312 }
313
314 // Double the capacity if we're below 1MB, or increase it by 1MB if
315 // we're above.
316 if (current_capacity_ < 1 * MB) {
317 current_capacity_ *= 2;
318 } else {
319 current_capacity_ += 1 * MB;
320 }
321 if (current_capacity_ > max_capacity_) {
322 current_capacity_ = max_capacity_;
323 }
324
325 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
326
327 SetFootprintLimit(current_capacity_);
328
329 return true;
330}
331
332// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
333// is already held.
334void* JitMemoryRegion::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
335 if (mspace == exec_mspace_) {
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100336 CHECK(exec_mspace_ != nullptr);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100337 const MemMap* const code_pages = GetUpdatableCodeMapping();
338 void* result = code_pages->Begin() + exec_end_;
339 exec_end_ += increment;
340 return result;
341 } else {
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100342 CHECK_EQ(data_mspace_, mspace);
343 const MemMap* const writable_data_pages = GetWritableDataMapping();
344 void* result = writable_data_pages->Begin() + data_end_;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100345 data_end_ += increment;
346 return result;
347 }
348}
349
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100350const uint8_t* JitMemoryRegion::AllocateCode(const uint8_t* code,
351 size_t code_size,
352 const uint8_t* stack_map,
353 bool has_should_deoptimize_flag) {
354 ScopedCodeCacheWrite scc(*this);
355
Orion Hodsone764f382019-06-27 12:56:48 +0100356 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100357 // Ensure the header ends up at expected instruction alignment.
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100358 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
359 size_t total_size = header_size + code_size;
360
361 // Each allocation should be on its own set of cache lines.
362 // `total_size` covers the OatQuickMethodHeader, the JIT generated machine code,
363 // and any alignment padding.
364 DCHECK_GT(total_size, header_size);
365 uint8_t* w_memory = reinterpret_cast<uint8_t*>(
366 mspace_memalign(exec_mspace_, alignment, total_size));
367 if (w_memory == nullptr) {
368 return nullptr;
369 }
370 uint8_t* x_memory = GetExecutableAddress(w_memory);
371 // Ensure the header ends up at expected instruction alignment.
372 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(w_memory + header_size), alignment);
373 used_memory_for_code_ += mspace_usable_size(w_memory);
374 const uint8_t* result = x_memory + header_size;
375
376 // Write the code.
377 std::copy(code, code + code_size, w_memory + header_size);
378
379 // Write the header.
380 OatQuickMethodHeader* method_header =
381 OatQuickMethodHeader::FromCodePointer(w_memory + header_size);
382 new (method_header) OatQuickMethodHeader(
383 (stack_map != nullptr) ? result - stack_map : 0u,
384 code_size);
385 if (has_should_deoptimize_flag) {
386 method_header->SetHasShouldDeoptimizeFlag();
387 }
388
389 // Both instruction and data caches need flushing to the point of unification where both share
390 // a common view of memory. Flushing the data cache ensures the dirty cachelines from the
391 // newly added code are written out to the point of unification. Flushing the instruction
392 // cache ensures the newly written code will be fetched from the point of unification before
393 // use. Memory in the code cache is re-cycled as code is added and removed. The flushes
394 // prevent stale code from residing in the instruction cache.
395 //
396 // Caches are flushed before write permission is removed because some ARMv8 Qualcomm kernels
397 // may trigger a segfault if a page fault occurs when requesting a cache maintenance
398 // operation. This is a kernel bug that we need to work around until affected devices
399 // (e.g. Nexus 5X and 6P) stop being supported or their kernels are fixed.
400 //
401 // For reference, this behavior is caused by this commit:
402 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
403 //
Orion Hodsonaeb02232019-06-25 14:18:18 +0100404 bool cache_flush_success = true;
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100405 if (HasDualCodeMapping()) {
Orion Hodsonaeb02232019-06-25 14:18:18 +0100406 // Flush d-cache for the non-executable mapping.
407 cache_flush_success = FlushCpuCaches(w_memory, w_memory + total_size);
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100408 }
409
Orion Hodsonaeb02232019-06-25 14:18:18 +0100410 // Invalidate i-cache for the executable mapping.
411 if (cache_flush_success) {
412 cache_flush_success = FlushCpuCaches(x_memory, x_memory + total_size);
413 }
414
415 // If flushing the cache has failed, reject the allocation because we can't guarantee
416 // correctness of the instructions present in the processor caches.
417 if (!cache_flush_success) {
418 PLOG(ERROR) << "Cache flush failed triggering code allocation failure";
419 FreeCode(x_memory);
420 return nullptr;
421 }
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100422
423 // Ensure CPU instruction pipelines are flushed for all cores. This is necessary for
424 // correctness as code may still be in instruction pipelines despite the i-cache flush. It is
425 // not safe to assume that changing permissions with mprotect (RX->RWX->RX) will cause a TLB
426 // shootdown (incidentally invalidating the CPU pipelines by sending an IPI to all cores to
427 // notify them of the TLB invalidation). Some architectures, notably ARM and ARM64, have
428 // hardware support that broadcasts TLB invalidations and so their kernels have no software
429 // based TLB shootdown. The sync-core flavor of membarrier was introduced in Linux 4.16 to
430 // address this (see mbarrier(2)). The membarrier here will fail on prior kernels and on
431 // platforms lacking the appropriate support.
432 art::membarrier(art::MembarrierCommand::kPrivateExpeditedSyncCore);
433
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100434 return result;
435}
436
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100437static void FillRootTable(uint8_t* roots_data, const std::vector<Handle<mirror::Object>>& roots)
438 REQUIRES(Locks::jit_lock_)
439 REQUIRES_SHARED(Locks::mutator_lock_) {
440 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
441 const uint32_t length = roots.size();
442 // Put all roots in `roots_data`.
443 for (uint32_t i = 0; i < length; ++i) {
444 ObjPtr<mirror::Object> object = roots[i].Get();
445 gc_roots[i] = GcRoot<mirror::Object>(object);
446 }
447 // Store the length of the table at the end. This will allow fetching it from a stack_map
448 // pointer.
449 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
450}
451
Orion Hodsonaeb02232019-06-25 14:18:18 +0100452bool JitMemoryRegion::CommitData(uint8_t* roots_data,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100453 const std::vector<Handle<mirror::Object>>& roots,
454 const uint8_t* stack_map,
455 size_t stack_map_size) {
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100456 roots_data = GetWritableDataAddress(roots_data);
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100457 size_t root_table_size = ComputeRootTableSize(roots.size());
458 uint8_t* stack_map_data = roots_data + root_table_size;
459 FillRootTable(roots_data, roots);
460 memcpy(stack_map_data, stack_map, stack_map_size);
461 // Flush data cache, as compiled code references literals in it.
Orion Hodsonaeb02232019-06-25 14:18:18 +0100462 // TODO(oth): establish whether this is necessary.
463 if (UNLIKELY(!FlushCpuCaches(roots_data, roots_data + root_table_size + stack_map_size))) {
464 VLOG(jit) << "Failed to flush data in CommitData";
465 return false;
466 }
467 return true;
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100468}
469
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100470void JitMemoryRegion::FreeCode(const uint8_t* code) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100471 code = GetNonExecutableAddress(code);
472 used_memory_for_code_ -= mspace_usable_size(code);
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100473 mspace_free(exec_mspace_, const_cast<uint8_t*>(code));
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100474}
475
476uint8_t* JitMemoryRegion::AllocateData(size_t data_size) {
477 void* result = mspace_malloc(data_mspace_, data_size);
478 used_memory_for_data_ += mspace_usable_size(result);
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100479 return reinterpret_cast<uint8_t*>(GetNonWritableDataAddress(result));
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100480}
481
482void JitMemoryRegion::FreeData(uint8_t* data) {
Nicolas Geoffrayac933ed2019-06-26 13:36:37 +0100483 data = GetWritableDataAddress(data);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100484 used_memory_for_data_ -= mspace_usable_size(data);
485 mspace_free(data_mspace_, data);
486}
487
Nicolas Geoffrayab682a72019-07-04 10:11:55 +0100488#if defined(__BIONIC__) && defined(ART_TARGET)
489// The code below only works on bionic on target.
Nicolas Geoffray2411f492019-06-14 08:54:46 +0100490
Orion Hodsond17eac62019-07-03 17:39:12 +0100491bool CacheOperationsMaySegFault() {
492#if defined(__linux__) && defined(__aarch64__)
493 // Avoid issue on older ARM64 kernels where data cache operations could be classified as writes
494 // and cause segmentation faults. This was fixed in Linux 3.11rc2:
495 //
496 // https://github.com/torvalds/linux/commit/db6f41063cbdb58b14846e600e6bc3f4e4c2e888
497 //
498 // This behaviour means we should avoid the dual view JIT on the device. This is just
499 // an issue when running tests on devices that have an old kernel.
500 static constexpr int kRequiredMajor = 3;
501 static constexpr int kRequiredMinor = 12;
502 struct utsname uts;
503 int major, minor;
504 if (uname(&uts) != 0 ||
505 strcmp(uts.sysname, "Linux") != 0 ||
506 sscanf(uts.release, "%d.%d", &major, &minor) != 2 ||
507 (major < kRequiredMajor || (major == kRequiredMajor && minor < kRequiredMinor))) {
508 return true;
509 }
510#endif
511 return false;
512}
513
Nicolas Geoffray2411f492019-06-14 08:54:46 +0100514int JitMemoryRegion::CreateZygoteMemory(size_t capacity, std::string* error_msg) {
Orion Hodsond17eac62019-07-03 17:39:12 +0100515 if (CacheOperationsMaySegFault()) {
516 // Zygote JIT requires dual code mappings by design. We can only do this if the cache flush
517 // and invalidate instructions work without raising faults.
518 *error_msg = "Zygote memory only works with dual mappings";
519 return -1;
520 }
Nicolas Geoffray2411f492019-06-14 08:54:46 +0100521 /* Check if kernel support exists, otherwise fall back to ashmem */
522 static const char* kRegionName = "/jit-zygote-cache";
Nicolas Geoffray3a614ea2019-06-27 15:47:09 +0100523 if (art::IsSealFutureWriteSupported()) {
Nicolas Geoffray2411f492019-06-14 08:54:46 +0100524 int fd = art::memfd_create(kRegionName, MFD_ALLOW_SEALING);
525 if (fd == -1) {
526 std::ostringstream oss;
527 oss << "Failed to create zygote mapping: " << strerror(errno);
528 *error_msg = oss.str();
529 return -1;
530 }
531
532 if (ftruncate(fd, capacity) != 0) {
533 std::ostringstream oss;
534 oss << "Failed to create zygote mapping: " << strerror(errno);
535 *error_msg = oss.str();
536 return -1;
537 }
538
539 return fd;
540 }
541
542 LOG(INFO) << "Falling back to ashmem implementation for JIT zygote mapping";
543
544 int fd;
545 PaletteStatus status = PaletteAshmemCreateRegion(kRegionName, capacity, &fd);
546 if (status != PaletteStatus::kOkay) {
547 CHECK_EQ(status, PaletteStatus::kCheckErrno);
548 std::ostringstream oss;
549 oss << "Failed to create zygote mapping: " << strerror(errno);
550 *error_msg = oss.str();
551 return -1;
552 }
553 return fd;
554}
555
556bool JitMemoryRegion::ProtectZygoteMemory(int fd, std::string* error_msg) {
Nicolas Geoffray3a614ea2019-06-27 15:47:09 +0100557 if (art::IsSealFutureWriteSupported()) {
Nicolas Geoffray2411f492019-06-14 08:54:46 +0100558 if (fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL | F_SEAL_FUTURE_WRITE)
559 == -1) {
560 std::ostringstream oss;
561 oss << "Failed to protect zygote mapping: " << strerror(errno);
562 *error_msg = oss.str();
563 return false;
564 }
565 } else {
566 PaletteStatus status = PaletteAshmemSetProtRegion(fd, PROT_READ);
567 if (status != PaletteStatus::kOkay) {
568 CHECK_EQ(status, PaletteStatus::kCheckErrno);
569 std::ostringstream oss;
570 oss << "Failed to protect zygote mapping: " << strerror(errno);
571 *error_msg = oss.str();
572 return false;
573 }
574 }
575 return true;
576}
577
578#else
579
Nicolas Geoffrayaf213cc2019-07-01 10:50:55 +0100580int JitMemoryRegion::CreateZygoteMemory(size_t capacity, std::string* error_msg) {
581 // To simplify host building, we don't rely on the latest memfd features.
582 LOG(WARNING) << "Returning un-sealable region on non-bionic";
583 static const char* kRegionName = "/jit-zygote-cache";
584 int fd = art::memfd_create(kRegionName, 0);
585 if (fd == -1) {
586 std::ostringstream oss;
587 oss << "Failed to create zygote mapping: " << strerror(errno);
588 *error_msg = oss.str();
589 return -1;
590 }
591 if (ftruncate(fd, capacity) != 0) {
592 std::ostringstream oss;
593 oss << "Failed to create zygote mapping: " << strerror(errno);
594 *error_msg = oss.str();
595 return -1;
596 }
597 return fd;
Nicolas Geoffray2411f492019-06-14 08:54:46 +0100598}
599
600bool JitMemoryRegion::ProtectZygoteMemory(int fd ATTRIBUTE_UNUSED,
601 std::string* error_msg ATTRIBUTE_UNUSED) {
602 return true;
603}
604
605#endif
606
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100607} // namespace jit
608} // namespace art