blob: 9ba1d6c1399c23dd71823ca6041c0f7878ceec20 [file] [log] [blame]
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001/*
2 * Copyright (C) 2008 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 "mem_map.h"
18
Ian Rogersc7dd2952014-10-21 23:31:19 -070019#include <inttypes.h>
Josh Gao0389cd52015-09-16 16:27:00 -070020#include <stdlib.h>
Andreas Gampe0dfc3152017-04-24 07:58:06 -070021#include <sys/mman.h> // For the PROT_* and MAP_* constants.
22#ifndef ANDROID_OS
23#include <sys/resource.h>
24#endif
Ian Rogersc7dd2952014-10-21 23:31:19 -070025
Andreas Gampe3b7dc352017-06-06 20:02:03 -070026#include <map>
Ian Rogers700a4022014-05-19 16:49:03 -070027#include <memory>
Ian Rogersc7dd2952014-10-21 23:31:19 -070028#include <sstream>
Elliott Hughesecd3a6f2012-06-06 18:16:37 -070029
Andreas Gampe46ee31b2016-12-14 10:11:49 -080030#include "android-base/stringprintf.h"
Andreas Gampe0dfc3152017-04-24 07:58:06 -070031#include "android-base/unique_fd.h"
Andreas Gampe0dfc3152017-04-24 07:58:06 -070032#include "cutils/ashmem.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080033
David Sehr1979c642018-04-26 14:41:18 -070034#include "allocator.h"
35#include "bit_utils.h"
36#include "globals.h"
37#include "logging.h" // For VLOG_IS_ON.
38#include "memory_tool.h"
39#include "utils.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080040
Ian Rogersd6b68652014-06-23 14:07:03 -070041#ifndef MAP_ANONYMOUS
42#define MAP_ANONYMOUS MAP_ANON
43#endif
44
Brian Carlstrom27ec9612011-09-19 20:20:38 -070045namespace art {
46
Andreas Gampe46ee31b2016-12-14 10:11:49 -080047using android::base::StringPrintf;
Andreas Gampe0dfc3152017-04-24 07:58:06 -070048using android::base::unique_fd;
49
Andreas Gampe3b7dc352017-06-06 20:02:03 -070050template<class Key, class T, AllocatorTag kTag, class Compare = std::less<Key>>
51using AllocationTrackingMultiMap =
52 std::multimap<Key, T, Compare, TrackingAllocator<std::pair<const Key, T>, kTag>>;
53
Andreas Gampe0dfc3152017-04-24 07:58:06 -070054using Maps = AllocationTrackingMultiMap<void*, MemMap*, kAllocatorTagMaps>;
55
56// All the non-empty MemMaps. Use a multimap as we do a reserve-and-divide (eg ElfMap::Load()).
57static Maps* gMaps GUARDED_BY(MemMap::GetMemMapsLock()) = nullptr;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080058
Andreas Gampe0dfc3152017-04-24 07:58:06 -070059std::ostream& operator<<(std::ostream& os, const Maps& mem_maps) {
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -070060 os << "MemMap:" << std::endl;
61 for (auto it = mem_maps.begin(); it != mem_maps.end(); ++it) {
62 void* base = it->first;
63 MemMap* map = it->second;
64 CHECK_EQ(base, map->BaseBegin());
65 os << *map << std::endl;
66 }
67 return os;
68}
69
David Sehr1b14fb82017-02-01 10:42:11 -080070std::mutex* MemMap::mem_maps_lock_ = nullptr;
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -070071
Ian Rogersc3ccc102014-06-25 11:52:14 -070072#if USE_ART_LOW_4G_ALLOCATOR
Andreas Gamped8f26db2014-05-19 17:01:13 -070073// Handling mem_map in 32b address range for 64b architectures that do not support MAP_32BIT.
74
75// The regular start of memory allocations. The first 64KB is protected by SELinux.
Andreas Gampe6bd621a2014-05-16 17:28:58 -070076static constexpr uintptr_t LOW_MEM_START = 64 * KB;
Andreas Gampe7104cbf2014-03-21 11:44:43 -070077
Andreas Gamped8f26db2014-05-19 17:01:13 -070078// Generate random starting position.
79// To not interfere with image position, take the image's address and only place it below. Current
80// formula (sketch):
81//
82// ART_BASE_ADDR = 0001XXXXXXXXXXXXXXX
83// ----------------------------------------
84// = 0000111111111111111
85// & ~(kPageSize - 1) =~0000000000000001111
86// ----------------------------------------
87// mask = 0000111111111110000
88// & random data = YYYYYYYYYYYYYYYYYYY
89// -----------------------------------
90// tmp = 0000YYYYYYYYYYY0000
91// + LOW_MEM_START = 0000000000001000000
92// --------------------------------------
93// start
94//
Josh Gao0389cd52015-09-16 16:27:00 -070095// arc4random as an entropy source is exposed in Bionic, but not in glibc. When we
Andreas Gamped8f26db2014-05-19 17:01:13 -070096// do not have Bionic, simply start with LOW_MEM_START.
97
98// Function is standalone so it can be tested somewhat in mem_map_test.cc.
99#ifdef __BIONIC__
100uintptr_t CreateStartPos(uint64_t input) {
101 CHECK_NE(0, ART_BASE_ADDRESS);
102
103 // Start with all bits below highest bit in ART_BASE_ADDRESS.
104 constexpr size_t leading_zeros = CLZ(static_cast<uint32_t>(ART_BASE_ADDRESS));
105 constexpr uintptr_t mask_ones = (1 << (31 - leading_zeros)) - 1;
106
107 // Lowest (usually 12) bits are not used, as aligned by page size.
108 constexpr uintptr_t mask = mask_ones & ~(kPageSize - 1);
109
110 // Mask input data.
111 return (input & mask) + LOW_MEM_START;
112}
113#endif
114
115static uintptr_t GenerateNextMemPos() {
116#ifdef __BIONIC__
Josh Gao0389cd52015-09-16 16:27:00 -0700117 uint64_t random_data;
118 arc4random_buf(&random_data, sizeof(random_data));
119 return CreateStartPos(random_data);
Andreas Gamped8f26db2014-05-19 17:01:13 -0700120#else
Josh Gao0389cd52015-09-16 16:27:00 -0700121 // No arc4random on host, see above.
Andreas Gamped8f26db2014-05-19 17:01:13 -0700122 return LOW_MEM_START;
123#endif
124}
125
126// Initialize linear scan to random position.
127uintptr_t MemMap::next_mem_pos_ = GenerateNextMemPos();
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000128#endif
129
Mathieu Chartier24a0fc82015-10-13 16:38:52 -0700130// Return true if the address range is contained in a single memory map by either reading
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700131// the gMaps variable or the /proc/self/map entry.
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700132bool MemMap::ContainedWithinExistingMap(uint8_t* ptr, size_t size, std::string* error_msg) {
Vladimir Marko5c42c292015-02-25 12:02:49 +0000133 uintptr_t begin = reinterpret_cast<uintptr_t>(ptr);
134 uintptr_t end = begin + size;
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700135
136 {
David Sehr1b14fb82017-02-01 10:42:11 -0800137 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700138 for (auto& pair : *gMaps) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700139 MemMap* const map = pair.second;
140 if (begin >= reinterpret_cast<uintptr_t>(map->Begin()) &&
141 end <= reinterpret_cast<uintptr_t>(map->End())) {
142 return true;
143 }
144 }
145 }
146
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800147 if (error_msg != nullptr) {
148 PrintFileToLog("/proc/self/maps", LogSeverity::ERROR);
149 *error_msg = StringPrintf("Requested region 0x%08" PRIxPTR "-0x%08" PRIxPTR " does not overlap "
150 "any existing map. See process maps in the log.", begin, end);
151 }
Jim_Guoa62a5882014-04-28 11:11:57 +0800152 return false;
153}
154
Jim_Guoa62a5882014-04-28 11:11:57 +0800155// CheckMapRequest to validate a non-MAP_FAILED mmap result based on
156// the expected value, calling munmap if validation fails, giving the
157// reason in error_msg.
158//
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700159// If the expected_ptr is null, nothing is checked beyond the fact
Jim_Guoa62a5882014-04-28 11:11:57 +0800160// that the actual_ptr is not MAP_FAILED. However, if expected_ptr is
161// non-null, we check that pointer is the actual_ptr == expected_ptr,
162// and if not, report in error_msg what the conflict mapping was if
163// found, or a generic error in other cases.
Ian Rogers13735952014-10-08 12:43:28 -0700164static bool CheckMapRequest(uint8_t* expected_ptr, void* actual_ptr, size_t byte_count,
Jim_Guoa62a5882014-04-28 11:11:57 +0800165 std::string* error_msg) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700166 // Handled first by caller for more specific error messages.
167 CHECK(actual_ptr != MAP_FAILED);
168
169 if (expected_ptr == nullptr) {
170 return true;
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700171 }
Elliott Hughesecd3a6f2012-06-06 18:16:37 -0700172
Jim_Guoa62a5882014-04-28 11:11:57 +0800173 uintptr_t actual = reinterpret_cast<uintptr_t>(actual_ptr);
174 uintptr_t expected = reinterpret_cast<uintptr_t>(expected_ptr);
Jim_Guoa62a5882014-04-28 11:11:57 +0800175
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700176 if (expected_ptr == actual_ptr) {
177 return true;
178 }
179
180 // We asked for an address but didn't get what we wanted, all paths below here should fail.
181 int result = munmap(actual_ptr, byte_count);
182 if (result == -1) {
183 PLOG(WARNING) << StringPrintf("munmap(%p, %zd) failed", actual_ptr, byte_count);
184 }
185
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800186 if (error_msg != nullptr) {
Mathieu Chartier83723ae2016-02-24 10:09:23 -0800187 // We call this here so that we can try and generate a full error
188 // message with the overlapping mapping. There's no guarantee that
189 // that there will be an overlap though, since
190 // - The kernel is not *required* to honor expected_ptr unless MAP_FIXED is
191 // true, even if there is no overlap
192 // - There might have been an overlap at the point of mmap, but the
193 // overlapping region has since been unmapped.
David Sehr2300b2d2018-05-10 14:20:10 -0700194
195 // Tell the client the mappings that were in place at the time.
196 if (kIsDebugBuild) {
197 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
198 }
199
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800200 std::ostringstream os;
201 os << StringPrintf("Failed to mmap at expected address, mapped at "
202 "0x%08" PRIxPTR " instead of 0x%08" PRIxPTR,
203 actual, expected);
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800204 *error_msg = os.str();
Christopher Ferris943af7d2014-01-16 12:41:46 -0800205 }
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700206 return false;
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700207}
208
Mathieu Chartier38c82212015-06-04 16:22:41 -0700209#if USE_ART_LOW_4G_ALLOCATOR
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800210static inline void* TryMemMapLow4GB(void* ptr,
211 size_t page_aligned_byte_count,
212 int prot,
213 int flags,
214 int fd,
215 off_t offset) {
216 void* actual = mmap(ptr, page_aligned_byte_count, prot, flags, fd, offset);
Mathieu Chartier38c82212015-06-04 16:22:41 -0700217 if (actual != MAP_FAILED) {
218 // Since we didn't use MAP_FIXED the kernel may have mapped it somewhere not in the low
219 // 4GB. If this is the case, unmap and retry.
220 if (reinterpret_cast<uintptr_t>(actual) + page_aligned_byte_count >= 4 * GB) {
221 munmap(actual, page_aligned_byte_count);
222 actual = MAP_FAILED;
223 }
224 }
225 return actual;
226}
227#endif
228
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800229MemMap* MemMap::MapAnonymous(const char* name,
230 uint8_t* expected_ptr,
231 size_t byte_count,
232 int prot,
233 bool low_4gb,
234 bool reuse,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000235 std::string* error_msg,
236 bool use_ashmem) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700237#ifndef __LP64__
238 UNUSED(low_4gb);
239#endif
Nicolas Geoffray58a73d22016-11-29 21:49:43 +0000240 use_ashmem = use_ashmem && !kIsTargetLinux;
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700241 if (byte_count == 0) {
Jim_Guoa62a5882014-04-28 11:11:57 +0800242 return new MemMap(name, nullptr, 0, nullptr, 0, prot, false);
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700243 }
Elliott Hughesecd3a6f2012-06-06 18:16:37 -0700244 size_t page_aligned_byte_count = RoundUp(byte_count, kPageSize);
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800245
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800246 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
Vladimir Marko5c42c292015-02-25 12:02:49 +0000247 if (reuse) {
248 // reuse means it is okay that it overlaps an existing page mapping.
249 // Only use this if you actually made the page reservation yourself.
250 CHECK(expected_ptr != nullptr);
251
Vladimir Markob5505822015-05-08 11:10:16 +0100252 DCHECK(ContainedWithinExistingMap(expected_ptr, byte_count, error_msg)) << *error_msg;
Vladimir Marko5c42c292015-02-25 12:02:49 +0000253 flags |= MAP_FIXED;
254 }
255
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000256 if (use_ashmem) {
257 if (!kIsTargetBuild) {
Bilyan Borisov3071f802016-03-31 17:15:53 +0100258 // When not on Android (either host or assuming a linux target) ashmem is faked using
259 // files in /tmp. Ensure that such files won't fail due to ulimit restrictions. If they
260 // will then use a regular mmap.
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000261 struct rlimit rlimit_fsize;
262 CHECK_EQ(getrlimit(RLIMIT_FSIZE, &rlimit_fsize), 0);
263 use_ashmem = (rlimit_fsize.rlim_cur == RLIM_INFINITY) ||
264 (page_aligned_byte_count < rlimit_fsize.rlim_cur);
265 }
266 }
267
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700268 unique_fd fd;
269
270
Ian Rogers997f0f92014-06-21 22:58:05 -0700271 if (use_ashmem) {
272 // android_os_Debug.cpp read_mapinfo assumes all ashmem regions associated with the VM are
273 // prefixed "dalvik-".
274 std::string debug_friendly_name("dalvik-");
275 debug_friendly_name += name;
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700276 fd.reset(ashmem_create_region(debug_friendly_name.c_str(), page_aligned_byte_count));
Richard Uhlera5c61bf2016-10-24 15:54:44 +0100277
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700278 if (fd.get() == -1) {
Richard Uhlera5c61bf2016-10-24 15:54:44 +0100279 // We failed to create the ashmem region. Print a warning, but continue
280 // anyway by creating a true anonymous mmap with an fd of -1. It is
281 // better to use an unlabelled anonymous map than to fail to create a
282 // map at all.
283 PLOG(WARNING) << "ashmem_create_region failed for '" << name << "'";
284 } else {
285 // We succeeded in creating the ashmem region. Use the created ashmem
286 // region as backing for the mmap.
287 flags &= ~MAP_ANONYMOUS;
Ian Rogers997f0f92014-06-21 22:58:05 -0700288 }
Ian Rogers997f0f92014-06-21 22:58:05 -0700289 }
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000290
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700291 // We need to store and potentially set an error number for pretty printing of errors
292 int saved_errno = 0;
293
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800294 void* actual = MapInternal(expected_ptr,
295 page_aligned_byte_count,
296 prot,
297 flags,
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700298 fd.get(),
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800299 0,
300 low_4gb);
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700301 saved_errno = errno;
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000302
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700303 if (actual == MAP_FAILED) {
Mathieu Chartier83723ae2016-02-24 10:09:23 -0800304 if (error_msg != nullptr) {
Andreas Gampe7fa55782016-06-15 17:45:01 -0700305 if (kIsDebugBuild || VLOG_IS_ON(oat)) {
306 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
307 }
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700308
Mathieu Chartier83723ae2016-02-24 10:09:23 -0800309 *error_msg = StringPrintf("Failed anonymous mmap(%p, %zd, 0x%x, 0x%x, %d, 0): %s. "
310 "See process maps in the log.",
311 expected_ptr,
312 page_aligned_byte_count,
313 prot,
314 flags,
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700315 fd.get(),
Mathieu Chartier83723ae2016-02-24 10:09:23 -0800316 strerror(saved_errno));
317 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700318 return nullptr;
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700319 }
Jim_Guoa62a5882014-04-28 11:11:57 +0800320 if (!CheckMapRequest(expected_ptr, actual, page_aligned_byte_count, error_msg)) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700321 return nullptr;
322 }
Ian Rogers13735952014-10-08 12:43:28 -0700323 return new MemMap(name, reinterpret_cast<uint8_t*>(actual), byte_count, actual,
Mathieu Chartier01d4b502015-06-12 17:32:31 -0700324 page_aligned_byte_count, prot, reuse);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700325}
326
David Srbecky1baabf02015-06-16 17:12:34 +0000327MemMap* MemMap::MapDummy(const char* name, uint8_t* addr, size_t byte_count) {
328 if (byte_count == 0) {
329 return new MemMap(name, nullptr, 0, nullptr, 0, 0, false);
330 }
331 const size_t page_aligned_byte_count = RoundUp(byte_count, kPageSize);
332 return new MemMap(name, addr, byte_count, addr, page_aligned_byte_count, 0, true /* reuse */);
333}
334
Alex Lightca97ada2018-02-02 09:25:31 -0800335template<typename A, typename B>
336static ptrdiff_t PointerDiff(A* a, B* b) {
337 return static_cast<ptrdiff_t>(reinterpret_cast<intptr_t>(a) - reinterpret_cast<intptr_t>(b));
338}
339
340bool MemMap::ReplaceWith(MemMap** source_ptr, /*out*/std::string* error) {
341#if !HAVE_MREMAP_SYSCALL
342 UNUSED(source_ptr);
343 *error = "Cannot perform atomic replace because we are missing the required mremap syscall";
344 return false;
345#else // !HAVE_MREMAP_SYSCALL
346 CHECK(source_ptr != nullptr);
347 CHECK(*source_ptr != nullptr);
348 if (!MemMap::kCanReplaceMapping) {
349 *error = "Unable to perform atomic replace due to runtime environment!";
350 return false;
351 }
352 MemMap* source = *source_ptr;
353 // neither can be reuse.
354 if (source->reuse_ || reuse_) {
355 *error = "One or both mappings is not a real mmap!";
356 return false;
357 }
358 // TODO Support redzones.
359 if (source->redzone_size_ != 0 || redzone_size_ != 0) {
360 *error = "source and dest have different redzone sizes";
361 return false;
362 }
363 // Make sure they have the same offset from the actual mmap'd address
364 if (PointerDiff(BaseBegin(), Begin()) != PointerDiff(source->BaseBegin(), source->Begin())) {
365 *error =
366 "source starts at a different offset from the mmap. Cannot atomically replace mappings";
367 return false;
368 }
369 // mremap doesn't allow the final [start, end] to overlap with the initial [start, end] (it's like
370 // memcpy but the check is explicit and actually done).
371 if (source->BaseBegin() > BaseBegin() &&
372 reinterpret_cast<uint8_t*>(BaseBegin()) + source->BaseSize() >
373 reinterpret_cast<uint8_t*>(source->BaseBegin())) {
374 *error = "destination memory pages overlap with source memory pages";
375 return false;
376 }
377 // Change the protection to match the new location.
378 int old_prot = source->GetProtect();
379 if (!source->Protect(GetProtect())) {
380 *error = "Could not change protections for source to those required for dest.";
381 return false;
382 }
383
384 // Do the mremap.
385 void* res = mremap(/*old_address*/source->BaseBegin(),
386 /*old_size*/source->BaseSize(),
387 /*new_size*/source->BaseSize(),
388 /*flags*/MREMAP_MAYMOVE | MREMAP_FIXED,
389 /*new_address*/BaseBegin());
390 if (res == MAP_FAILED) {
391 int saved_errno = errno;
392 // Wasn't able to move mapping. Change the protection of source back to the original one and
393 // return.
394 source->Protect(old_prot);
395 *error = std::string("Failed to mremap source to dest. Error was ") + strerror(saved_errno);
396 return false;
397 }
398 CHECK(res == BaseBegin());
399
400 // The new base_size is all the pages of the 'source' plus any remaining dest pages. We will unmap
401 // them later.
402 size_t new_base_size = std::max(source->base_size_, base_size_);
403
404 // Delete the old source, don't unmap it though (set reuse) since it is already gone.
405 *source_ptr = nullptr;
406 size_t source_size = source->size_;
407 source->already_unmapped_ = true;
408 delete source;
409 source = nullptr;
410
411 size_ = source_size;
412 base_size_ = new_base_size;
413 // Reduce base_size if needed (this will unmap the extra pages).
414 SetSize(source_size);
415
416 return true;
417#endif // !HAVE_MREMAP_SYSCALL
418}
419
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800420MemMap* MemMap::MapFileAtAddress(uint8_t* expected_ptr,
421 size_t byte_count,
422 int prot,
423 int flags,
424 int fd,
425 off_t start,
426 bool low_4gb,
427 bool reuse,
428 const char* filename,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700429 std::string* error_msg) {
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700430 CHECK_NE(0, prot);
431 CHECK_NE(0, flags & (MAP_SHARED | MAP_PRIVATE));
Narayan Kamathb89c3da2014-08-21 17:38:09 +0100432
433 // Note that we do not allow MAP_FIXED unless reuse == true, i.e we
434 // expect his mapping to be contained within an existing map.
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700435 if (reuse) {
436 // reuse means it is okay that it overlaps an existing page mapping.
437 // Only use this if you actually made the page reservation yourself.
Jim_Guoa62a5882014-04-28 11:11:57 +0800438 CHECK(expected_ptr != nullptr);
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800439 DCHECK(error_msg != nullptr);
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800440 DCHECK(ContainedWithinExistingMap(expected_ptr, byte_count, error_msg))
441 << ((error_msg != nullptr) ? *error_msg : std::string());
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700442 flags |= MAP_FIXED;
443 } else {
444 CHECK_EQ(0, flags & MAP_FIXED);
Narayan Kamathb89c3da2014-08-21 17:38:09 +0100445 // Don't bother checking for an overlapping region here. We'll
446 // check this if required after the fact inside CheckMapRequest.
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700447 }
448
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700449 if (byte_count == 0) {
Jim_Guoa62a5882014-04-28 11:11:57 +0800450 return new MemMap(filename, nullptr, 0, nullptr, 0, prot, false);
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700451 }
Ian Rogersf8adc602013-04-18 17:06:19 -0700452 // Adjust 'offset' to be page-aligned as required by mmap.
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700453 int page_offset = start % kPageSize;
454 off_t page_aligned_offset = start - page_offset;
Ian Rogersf8adc602013-04-18 17:06:19 -0700455 // Adjust 'byte_count' to be page-aligned as we will map this anyway.
Elliott Hughesecd3a6f2012-06-06 18:16:37 -0700456 size_t page_aligned_byte_count = RoundUp(byte_count + page_offset, kPageSize);
Jim_Guoa62a5882014-04-28 11:11:57 +0800457 // The 'expected_ptr' is modified (if specified, ie non-null) to be page aligned to the file but
458 // not necessarily to virtual memory. mmap will page align 'expected' for us.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700459 uint8_t* page_aligned_expected =
460 (expected_ptr == nullptr) ? nullptr : (expected_ptr - page_offset);
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700461
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700462 size_t redzone_size = 0;
Roland Levillain05e34f42018-05-24 13:19:05 +0000463 if (kRunningOnMemoryTool && kMemoryToolAddsRedzones && expected_ptr == nullptr) {
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700464 redzone_size = kPageSize;
465 page_aligned_byte_count += redzone_size;
466 }
467
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800468 uint8_t* actual = reinterpret_cast<uint8_t*>(MapInternal(page_aligned_expected,
469 page_aligned_byte_count,
470 prot,
471 flags,
472 fd,
473 page_aligned_offset,
474 low_4gb));
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700475 if (actual == MAP_FAILED) {
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800476 if (error_msg != nullptr) {
477 auto saved_errno = errno;
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700478
Andreas Gampe7ec09042016-04-01 17:20:49 -0700479 if (kIsDebugBuild || VLOG_IS_ON(oat)) {
480 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
481 }
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700482
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800483 *error_msg = StringPrintf("mmap(%p, %zd, 0x%x, 0x%x, %d, %" PRId64
484 ") of file '%s' failed: %s. See process maps in the log.",
485 page_aligned_expected, page_aligned_byte_count, prot, flags, fd,
486 static_cast<int64_t>(page_aligned_offset), filename,
487 strerror(saved_errno));
488 }
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700489 return nullptr;
490 }
Jim_Guoa62a5882014-04-28 11:11:57 +0800491 if (!CheckMapRequest(expected_ptr, actual, page_aligned_byte_count, error_msg)) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700492 return nullptr;
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700493 }
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700494 if (redzone_size != 0) {
495 const uint8_t *real_start = actual + page_offset;
496 const uint8_t *real_end = actual + page_offset + byte_count;
497 const uint8_t *mapping_end = actual + page_aligned_byte_count;
498
499 MEMORY_TOOL_MAKE_NOACCESS(actual, real_start - actual);
500 MEMORY_TOOL_MAKE_NOACCESS(real_end, mapping_end - real_end);
501 page_aligned_byte_count -= redzone_size;
502 }
503
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800504 return new MemMap(filename, actual + page_offset, byte_count, actual, page_aligned_byte_count,
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700505 prot, reuse, redzone_size);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700506}
507
508MemMap::~MemMap() {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700509 if (base_begin_ == nullptr && base_size_ == 0) {
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700510 return;
511 }
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700512
513 // Unlike Valgrind, AddressSanitizer requires that all manually poisoned memory is unpoisoned
514 // before it is returned to the system.
515 if (redzone_size_ != 0) {
516 MEMORY_TOOL_MAKE_UNDEFINED(
517 reinterpret_cast<char*>(base_begin_) + base_size_ - redzone_size_,
518 redzone_size_);
519 }
520
Jim_Guoa62a5882014-04-28 11:11:57 +0800521 if (!reuse_) {
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700522 MEMORY_TOOL_MAKE_UNDEFINED(base_begin_, base_size_);
Alex Lightca97ada2018-02-02 09:25:31 -0800523 if (!already_unmapped_) {
524 int result = munmap(base_begin_, base_size_);
525 if (result == -1) {
526 PLOG(FATAL) << "munmap failed";
527 }
Jim_Guoa62a5882014-04-28 11:11:57 +0800528 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700529 }
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700530
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700531 // Remove it from gMaps.
David Sehr1b14fb82017-02-01 10:42:11 -0800532 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700533 bool found = false;
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700534 DCHECK(gMaps != nullptr);
535 for (auto it = gMaps->lower_bound(base_begin_), end = gMaps->end();
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700536 it != end && it->first == base_begin_; ++it) {
537 if (it->second == this) {
538 found = true;
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700539 gMaps->erase(it);
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700540 break;
541 }
542 }
543 CHECK(found) << "MemMap not found";
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700544}
545
Ian Rogers13735952014-10-08 12:43:28 -0700546MemMap::MemMap(const std::string& name, uint8_t* begin, size_t size, void* base_begin,
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700547 size_t base_size, int prot, bool reuse, size_t redzone_size)
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700548 : name_(name), begin_(begin), size_(size), base_begin_(base_begin), base_size_(base_size),
Alex Lightca97ada2018-02-02 09:25:31 -0800549 prot_(prot), reuse_(reuse), already_unmapped_(false), redzone_size_(redzone_size) {
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700550 if (size_ == 0) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700551 CHECK(begin_ == nullptr);
552 CHECK(base_begin_ == nullptr);
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700553 CHECK_EQ(base_size_, 0U);
554 } else {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700555 CHECK(begin_ != nullptr);
556 CHECK(base_begin_ != nullptr);
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700557 CHECK_NE(base_size_, 0U);
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700558
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700559 // Add it to gMaps.
David Sehr1b14fb82017-02-01 10:42:11 -0800560 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700561 DCHECK(gMaps != nullptr);
562 gMaps->insert(std::make_pair(base_begin_, this));
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700563 }
Andreas Gampec8ccf682014-09-29 20:07:43 -0700564}
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700565
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100566MemMap* MemMap::RemapAtEnd(uint8_t* new_end, const char* tail_name, int tail_prot,
567 std::string* error_msg, bool use_ashmem) {
Nicolas Geoffray58a73d22016-11-29 21:49:43 +0000568 use_ashmem = use_ashmem && !kIsTargetLinux;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700569 DCHECK_GE(new_end, Begin());
570 DCHECK_LE(new_end, End());
Ian Rogers13735952014-10-08 12:43:28 -0700571 DCHECK_LE(begin_ + size_, reinterpret_cast<uint8_t*>(base_begin_) + base_size_);
Roland Levillain14d90572015-07-16 10:52:26 +0100572 DCHECK_ALIGNED(begin_, kPageSize);
573 DCHECK_ALIGNED(base_begin_, kPageSize);
574 DCHECK_ALIGNED(reinterpret_cast<uint8_t*>(base_begin_) + base_size_, kPageSize);
575 DCHECK_ALIGNED(new_end, kPageSize);
Ian Rogers13735952014-10-08 12:43:28 -0700576 uint8_t* old_end = begin_ + size_;
577 uint8_t* old_base_end = reinterpret_cast<uint8_t*>(base_begin_) + base_size_;
578 uint8_t* new_base_end = new_end;
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700579 DCHECK_LE(new_base_end, old_base_end);
580 if (new_base_end == old_base_end) {
Jim_Guoa62a5882014-04-28 11:11:57 +0800581 return new MemMap(tail_name, nullptr, 0, nullptr, 0, tail_prot, false);
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700582 }
Ian Rogers13735952014-10-08 12:43:28 -0700583 size_ = new_end - reinterpret_cast<uint8_t*>(begin_);
584 base_size_ = new_base_end - reinterpret_cast<uint8_t*>(base_begin_);
585 DCHECK_LE(begin_ + size_, reinterpret_cast<uint8_t*>(base_begin_) + base_size_);
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700586 size_t tail_size = old_end - new_end;
Ian Rogers13735952014-10-08 12:43:28 -0700587 uint8_t* tail_base_begin = new_base_end;
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700588 size_t tail_base_size = old_base_end - new_base_end;
589 DCHECK_EQ(tail_base_begin + tail_base_size, old_base_end);
Roland Levillain14d90572015-07-16 10:52:26 +0100590 DCHECK_ALIGNED(tail_base_size, kPageSize);
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700591
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700592 unique_fd fd;
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100593 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000594 if (use_ashmem) {
595 // android_os_Debug.cpp read_mapinfo assumes all ashmem regions associated with the VM are
596 // prefixed "dalvik-".
597 std::string debug_friendly_name("dalvik-");
598 debug_friendly_name += tail_name;
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700599 fd.reset(ashmem_create_region(debug_friendly_name.c_str(), tail_base_size));
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100600 flags = MAP_PRIVATE | MAP_FIXED;
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700601 if (fd.get() == -1) {
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000602 *error_msg = StringPrintf("ashmem_create_region failed for '%s': %s",
603 tail_name, strerror(errno));
604 return nullptr;
605 }
606 }
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700607
608 MEMORY_TOOL_MAKE_UNDEFINED(tail_base_begin, tail_base_size);
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700609 // Unmap/map the tail region.
610 int result = munmap(tail_base_begin, tail_base_size);
611 if (result == -1) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800612 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
613 *error_msg = StringPrintf("munmap(%p, %zd) failed for '%s'. See process maps in the log.",
614 tail_base_begin, tail_base_size, name_.c_str());
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700615 return nullptr;
616 }
617 // Don't cause memory allocation between the munmap and the mmap
618 // calls. Otherwise, libc (or something else) might take this memory
619 // region. Note this isn't perfect as there's no way to prevent
620 // other threads to try to take this memory region here.
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700621 uint8_t* actual = reinterpret_cast<uint8_t*>(mmap(tail_base_begin,
622 tail_base_size,
623 tail_prot,
624 flags,
625 fd.get(),
626 0));
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700627 if (actual == MAP_FAILED) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800628 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
629 *error_msg = StringPrintf("anonymous mmap(%p, %zd, 0x%x, 0x%x, %d, 0) failed. See process "
630 "maps in the log.", tail_base_begin, tail_base_size, tail_prot, flags,
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700631 fd.get());
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700632 return nullptr;
633 }
Jim_Guoa62a5882014-04-28 11:11:57 +0800634 return new MemMap(tail_name, actual, tail_size, actual, tail_base_size, tail_prot, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700635}
Logan Chiend88fa262012-06-06 15:23:32 +0800636
Ian Rogersc5f17732014-06-05 20:48:42 -0700637void MemMap::MadviseDontNeedAndZero() {
638 if (base_begin_ != nullptr || base_size_ != 0) {
639 if (!kMadviseZeroes) {
640 memset(base_begin_, 0, base_size_);
641 }
642 int result = madvise(base_begin_, base_size_, MADV_DONTNEED);
643 if (result == -1) {
644 PLOG(WARNING) << "madvise failed";
645 }
646 }
647}
648
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000649bool MemMap::Sync() {
Hiroshi Yamauchi29ab3602016-03-08 15:17:21 -0800650 bool result;
651 if (redzone_size_ != 0) {
Roland Levillain05e34f42018-05-24 13:19:05 +0000652 // To avoid errors when running on a memory tool, temporarily lift the lower-end noaccess
653 // protection before passing it to msync() as it only accepts page-aligned base address,
654 // and exclude the higher-end noaccess protection from the msync range. b/27552451.
655 // TODO: Valgrind is no longer supported, but Address Sanitizer is:
656 // check whether this special case is needed for ASan.
Hiroshi Yamauchi29ab3602016-03-08 15:17:21 -0800657 uint8_t* base_begin = reinterpret_cast<uint8_t*>(base_begin_);
658 MEMORY_TOOL_MAKE_DEFINED(base_begin, begin_ - base_begin);
659 result = msync(BaseBegin(), End() - base_begin, MS_SYNC) == 0;
660 MEMORY_TOOL_MAKE_NOACCESS(base_begin, begin_ - base_begin);
661 } else {
662 result = msync(BaseBegin(), BaseSize(), MS_SYNC) == 0;
663 }
664 return result;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000665}
666
Logan Chiend88fa262012-06-06 15:23:32 +0800667bool MemMap::Protect(int prot) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700668 if (base_begin_ == nullptr && base_size_ == 0) {
Ian Rogers1c849e52012-06-28 14:00:33 -0700669 prot_ = prot;
Logan Chiend88fa262012-06-06 15:23:32 +0800670 return true;
671 }
672
673 if (mprotect(base_begin_, base_size_, prot) == 0) {
Ian Rogers1c849e52012-06-28 14:00:33 -0700674 prot_ = prot;
Logan Chiend88fa262012-06-06 15:23:32 +0800675 return true;
676 }
677
Shih-wei Liaoa060ed92012-06-07 09:25:28 -0700678 PLOG(ERROR) << "mprotect(" << reinterpret_cast<void*>(base_begin_) << ", " << base_size_ << ", "
679 << prot << ") failed";
Logan Chiend88fa262012-06-06 15:23:32 +0800680 return false;
681}
682
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700683bool MemMap::CheckNoGaps(MemMap* begin_map, MemMap* end_map) {
David Sehr1b14fb82017-02-01 10:42:11 -0800684 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700685 CHECK(begin_map != nullptr);
686 CHECK(end_map != nullptr);
687 CHECK(HasMemMap(begin_map));
688 CHECK(HasMemMap(end_map));
689 CHECK_LE(begin_map->BaseBegin(), end_map->BaseBegin());
690 MemMap* map = begin_map;
691 while (map->BaseBegin() != end_map->BaseBegin()) {
692 MemMap* next_map = GetLargestMemMapAt(map->BaseEnd());
693 if (next_map == nullptr) {
694 // Found a gap.
695 return false;
696 }
697 map = next_map;
698 }
699 return true;
700}
701
Vladimir Marko17a924a2015-05-08 15:17:32 +0100702void MemMap::DumpMaps(std::ostream& os, bool terse) {
David Sehr1b14fb82017-02-01 10:42:11 -0800703 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Vladimir Marko17a924a2015-05-08 15:17:32 +0100704 DumpMapsLocked(os, terse);
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700705}
706
Vladimir Marko17a924a2015-05-08 15:17:32 +0100707void MemMap::DumpMapsLocked(std::ostream& os, bool terse) {
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700708 const auto& mem_maps = *gMaps;
Vladimir Marko17a924a2015-05-08 15:17:32 +0100709 if (!terse) {
710 os << mem_maps;
711 return;
712 }
713
714 // Terse output example:
715 // [MemMap: 0x409be000+0x20P~0x11dP+0x20P~0x61cP+0x20P prot=0x3 LinearAlloc]
716 // [MemMap: 0x451d6000+0x6bP(3) prot=0x3 large object space allocation]
717 // The details:
718 // "+0x20P" means 0x20 pages taken by a single mapping,
719 // "~0x11dP" means a gap of 0x11d pages,
720 // "+0x6bP(3)" means 3 mappings one after another, together taking 0x6b pages.
721 os << "MemMap:" << std::endl;
722 for (auto it = mem_maps.begin(), maps_end = mem_maps.end(); it != maps_end;) {
723 MemMap* map = it->second;
724 void* base = it->first;
725 CHECK_EQ(base, map->BaseBegin());
726 os << "[MemMap: " << base;
727 ++it;
728 // Merge consecutive maps with the same protect flags and name.
729 constexpr size_t kMaxGaps = 9;
730 size_t num_gaps = 0;
731 size_t num = 1u;
732 size_t size = map->BaseSize();
Roland Levillain14d90572015-07-16 10:52:26 +0100733 CHECK_ALIGNED(size, kPageSize);
Vladimir Marko17a924a2015-05-08 15:17:32 +0100734 void* end = map->BaseEnd();
735 while (it != maps_end &&
736 it->second->GetProtect() == map->GetProtect() &&
737 it->second->GetName() == map->GetName() &&
738 (it->second->BaseBegin() == end || num_gaps < kMaxGaps)) {
739 if (it->second->BaseBegin() != end) {
740 ++num_gaps;
741 os << "+0x" << std::hex << (size / kPageSize) << "P";
742 if (num != 1u) {
743 os << "(" << std::dec << num << ")";
744 }
745 size_t gap =
746 reinterpret_cast<uintptr_t>(it->second->BaseBegin()) - reinterpret_cast<uintptr_t>(end);
Roland Levillain14d90572015-07-16 10:52:26 +0100747 CHECK_ALIGNED(gap, kPageSize);
Vladimir Marko17a924a2015-05-08 15:17:32 +0100748 os << "~0x" << std::hex << (gap / kPageSize) << "P";
749 num = 0u;
750 size = 0u;
751 }
Roland Levillain14d90572015-07-16 10:52:26 +0100752 CHECK_ALIGNED(it->second->BaseSize(), kPageSize);
Vladimir Marko17a924a2015-05-08 15:17:32 +0100753 ++num;
754 size += it->second->BaseSize();
755 end = it->second->BaseEnd();
756 ++it;
757 }
758 os << "+0x" << std::hex << (size / kPageSize) << "P";
759 if (num != 1u) {
760 os << "(" << std::dec << num << ")";
761 }
762 os << " prot=0x" << std::hex << map->GetProtect() << " " << map->GetName() << "]" << std::endl;
763 }
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700764}
765
766bool MemMap::HasMemMap(MemMap* map) {
767 void* base_begin = map->BaseBegin();
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700768 for (auto it = gMaps->lower_bound(base_begin), end = gMaps->end();
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700769 it != end && it->first == base_begin; ++it) {
770 if (it->second == map) {
771 return true;
772 }
773 }
774 return false;
775}
776
777MemMap* MemMap::GetLargestMemMapAt(void* address) {
778 size_t largest_size = 0;
779 MemMap* largest_map = nullptr;
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700780 DCHECK(gMaps != nullptr);
781 for (auto it = gMaps->lower_bound(address), end = gMaps->end();
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700782 it != end && it->first == address; ++it) {
783 MemMap* map = it->second;
784 CHECK(map != nullptr);
785 if (largest_size < map->BaseSize()) {
786 largest_size = map->BaseSize();
787 largest_map = map;
788 }
789 }
790 return largest_map;
791}
792
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700793void MemMap::Init() {
David Sehr1b14fb82017-02-01 10:42:11 -0800794 if (mem_maps_lock_ != nullptr) {
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700795 // dex2oat calls MemMap::Init twice since its needed before the runtime is created.
David Sehr1b14fb82017-02-01 10:42:11 -0800796 return;
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700797 }
David Sehr1b14fb82017-02-01 10:42:11 -0800798 mem_maps_lock_ = new std::mutex();
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700799 // Not for thread safety, but for the annotation that gMaps is GUARDED_BY(mem_maps_lock_).
David Sehr1b14fb82017-02-01 10:42:11 -0800800 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700801 DCHECK(gMaps == nullptr);
802 gMaps = new Maps;
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700803}
804
805void MemMap::Shutdown() {
David Sehr1b14fb82017-02-01 10:42:11 -0800806 if (mem_maps_lock_ == nullptr) {
807 // If MemMap::Shutdown is called more than once, there is no effect.
808 return;
809 }
810 {
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700811 // Not for thread safety, but for the annotation that gMaps is GUARDED_BY(mem_maps_lock_).
David Sehr1b14fb82017-02-01 10:42:11 -0800812 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700813 DCHECK(gMaps != nullptr);
814 delete gMaps;
815 gMaps = nullptr;
David Sehr1b14fb82017-02-01 10:42:11 -0800816 }
817 delete mem_maps_lock_;
818 mem_maps_lock_ = nullptr;
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700819}
820
Mathieu Chartier379d09f2015-01-08 11:28:13 -0800821void MemMap::SetSize(size_t new_size) {
Alex Lightca97ada2018-02-02 09:25:31 -0800822 CHECK_LE(new_size, size_);
823 size_t new_base_size = RoundUp(new_size + static_cast<size_t>(PointerDiff(Begin(), BaseBegin())),
824 kPageSize);
825 if (new_base_size == base_size_) {
826 size_ = new_size;
Mathieu Chartier379d09f2015-01-08 11:28:13 -0800827 return;
828 }
Alex Lightca97ada2018-02-02 09:25:31 -0800829 CHECK_LT(new_base_size, base_size_);
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700830 MEMORY_TOOL_MAKE_UNDEFINED(
831 reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(BaseBegin()) +
Alex Lightca97ada2018-02-02 09:25:31 -0800832 new_base_size),
833 base_size_ - new_base_size);
834 CHECK_EQ(munmap(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(BaseBegin()) + new_base_size),
835 base_size_ - new_base_size), 0) << new_base_size << " " << base_size_;
836 base_size_ = new_base_size;
Mathieu Chartier379d09f2015-01-08 11:28:13 -0800837 size_ = new_size;
838}
839
Andreas Gampe651ba592017-06-14 14:41:33 -0700840void* MemMap::MapInternalArtLow4GBAllocator(size_t length,
841 int prot,
842 int flags,
843 int fd,
844 off_t offset) {
845#if USE_ART_LOW_4G_ALLOCATOR
846 void* actual = MAP_FAILED;
847
848 bool first_run = true;
849
850 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
851 for (uintptr_t ptr = next_mem_pos_; ptr < 4 * GB; ptr += kPageSize) {
852 // Use gMaps as an optimization to skip over large maps.
853 // Find the first map which is address > ptr.
854 auto it = gMaps->upper_bound(reinterpret_cast<void*>(ptr));
855 if (it != gMaps->begin()) {
856 auto before_it = it;
857 --before_it;
858 // Start at the end of the map before the upper bound.
859 ptr = std::max(ptr, reinterpret_cast<uintptr_t>(before_it->second->BaseEnd()));
860 CHECK_ALIGNED(ptr, kPageSize);
861 }
862 while (it != gMaps->end()) {
863 // How much space do we have until the next map?
864 size_t delta = reinterpret_cast<uintptr_t>(it->first) - ptr;
865 // If the space may be sufficient, break out of the loop.
866 if (delta >= length) {
867 break;
868 }
869 // Otherwise, skip to the end of the map.
870 ptr = reinterpret_cast<uintptr_t>(it->second->BaseEnd());
871 CHECK_ALIGNED(ptr, kPageSize);
872 ++it;
873 }
874
875 // Try to see if we get lucky with this address since none of the ART maps overlap.
876 actual = TryMemMapLow4GB(reinterpret_cast<void*>(ptr), length, prot, flags, fd, offset);
877 if (actual != MAP_FAILED) {
878 next_mem_pos_ = reinterpret_cast<uintptr_t>(actual) + length;
879 return actual;
880 }
881
882 if (4U * GB - ptr < length) {
883 // Not enough memory until 4GB.
884 if (first_run) {
885 // Try another time from the bottom;
886 ptr = LOW_MEM_START - kPageSize;
887 first_run = false;
888 continue;
889 } else {
890 // Second try failed.
891 break;
892 }
893 }
894
895 uintptr_t tail_ptr;
896
897 // Check pages are free.
898 bool safe = true;
899 for (tail_ptr = ptr; tail_ptr < ptr + length; tail_ptr += kPageSize) {
900 if (msync(reinterpret_cast<void*>(tail_ptr), kPageSize, 0) == 0) {
901 safe = false;
902 break;
903 } else {
904 DCHECK_EQ(errno, ENOMEM);
905 }
906 }
907
908 next_mem_pos_ = tail_ptr; // update early, as we break out when we found and mapped a region
909
910 if (safe == true) {
911 actual = TryMemMapLow4GB(reinterpret_cast<void*>(ptr), length, prot, flags, fd, offset);
912 if (actual != MAP_FAILED) {
913 return actual;
914 }
915 } else {
916 // Skip over last page.
917 ptr = tail_ptr;
918 }
919 }
920
921 if (actual == MAP_FAILED) {
922 LOG(ERROR) << "Could not find contiguous low-memory space.";
923 errno = ENOMEM;
924 }
925 return actual;
926#else
927 UNUSED(length, prot, flags, fd, offset);
928 LOG(FATAL) << "Unreachable";
929 UNREACHABLE();
930#endif
931}
932
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800933void* MemMap::MapInternal(void* addr,
934 size_t length,
935 int prot,
936 int flags,
937 int fd,
938 off_t offset,
939 bool low_4gb) {
940#ifdef __LP64__
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800941 // When requesting low_4g memory and having an expectation, the requested range should fit into
942 // 4GB.
943 if (low_4gb && (
944 // Start out of bounds.
945 (reinterpret_cast<uintptr_t>(addr) >> 32) != 0 ||
946 // End out of bounds. For simplicity, this will fail for the last page of memory.
947 ((reinterpret_cast<uintptr_t>(addr) + length) >> 32) != 0)) {
948 LOG(ERROR) << "The requested address space (" << addr << ", "
949 << reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(addr) + length)
950 << ") cannot fit in low_4gb";
951 return MAP_FAILED;
952 }
953#else
954 UNUSED(low_4gb);
955#endif
956 DCHECK_ALIGNED(length, kPageSize);
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800957 // TODO:
958 // A page allocator would be a useful abstraction here, as
959 // 1) It is doubtful that MAP_32BIT on x86_64 is doing the right job for us
960 void* actual = MAP_FAILED;
961#if USE_ART_LOW_4G_ALLOCATOR
962 // MAP_32BIT only available on x86_64.
963 if (low_4gb && addr == nullptr) {
Andreas Gampe651ba592017-06-14 14:41:33 -0700964 // The linear-scan allocator has an issue when executable pages are denied (e.g., by selinux
965 // policies in sensitive processes). In that case, the error code will still be ENOMEM. So
966 // the allocator will scan all low 4GB twice, and still fail. This is *very* slow.
967 //
968 // To avoid the issue, always map non-executable first, and mprotect if necessary.
969 const int orig_prot = prot;
970 const int prot_non_exec = prot & ~PROT_EXEC;
971 actual = MapInternalArtLow4GBAllocator(length, prot_non_exec, flags, fd, offset);
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800972
973 if (actual == MAP_FAILED) {
Andreas Gampe651ba592017-06-14 14:41:33 -0700974 return MAP_FAILED;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800975 }
Andreas Gampe651ba592017-06-14 14:41:33 -0700976
977 // See if we need to remap with the executable bit now.
978 if (orig_prot != prot_non_exec) {
979 if (mprotect(actual, length, orig_prot) != 0) {
980 PLOG(ERROR) << "Could not protect to requested prot: " << orig_prot;
981 munmap(actual, length);
982 errno = ENOMEM;
983 return MAP_FAILED;
984 }
985 }
986 return actual;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800987 }
988
Andreas Gampe651ba592017-06-14 14:41:33 -0700989 actual = mmap(addr, length, prot, flags, fd, offset);
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800990#else
991#if defined(__LP64__)
992 if (low_4gb && addr == nullptr) {
993 flags |= MAP_32BIT;
994 }
995#endif
996 actual = mmap(addr, length, prot, flags, fd, offset);
997#endif
998 return actual;
999}
1000
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001001std::ostream& operator<<(std::ostream& os, const MemMap& mem_map) {
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -07001002 os << StringPrintf("[MemMap: %p-%p prot=0x%x %s]",
1003 mem_map.BaseBegin(), mem_map.BaseEnd(), mem_map.GetProtect(),
1004 mem_map.GetName().c_str());
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001005 return os;
1006}
1007
Hiroshi Yamauchi6edb9ae2016-02-08 14:18:21 -08001008void MemMap::TryReadable() {
1009 if (base_begin_ == nullptr && base_size_ == 0) {
1010 return;
1011 }
1012 CHECK_NE(prot_ & PROT_READ, 0);
1013 volatile uint8_t* begin = reinterpret_cast<volatile uint8_t*>(base_begin_);
1014 volatile uint8_t* end = begin + base_size_;
1015 DCHECK(IsAligned<kPageSize>(begin));
1016 DCHECK(IsAligned<kPageSize>(end));
1017 // Read the first byte of each page. Use volatile to prevent the compiler from optimizing away the
1018 // reads.
1019 for (volatile uint8_t* ptr = begin; ptr < end; ptr += kPageSize) {
1020 // This read could fault if protection wasn't set correctly.
1021 uint8_t value = *ptr;
1022 UNUSED(value);
1023 }
1024}
1025
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07001026void ZeroAndReleasePages(void* address, size_t length) {
Mathieu Chartier7c928f02017-06-05 17:23:44 -07001027 if (length == 0) {
1028 return;
1029 }
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07001030 uint8_t* const mem_begin = reinterpret_cast<uint8_t*>(address);
1031 uint8_t* const mem_end = mem_begin + length;
1032 uint8_t* const page_begin = AlignUp(mem_begin, kPageSize);
1033 uint8_t* const page_end = AlignDown(mem_end, kPageSize);
1034 if (!kMadviseZeroes || page_begin >= page_end) {
1035 // No possible area to madvise.
1036 std::fill(mem_begin, mem_end, 0);
1037 } else {
1038 // Spans one or more pages.
1039 DCHECK_LE(mem_begin, page_begin);
1040 DCHECK_LE(page_begin, page_end);
1041 DCHECK_LE(page_end, mem_end);
1042 std::fill(mem_begin, page_begin, 0);
1043 CHECK_NE(madvise(page_begin, page_end - page_begin, MADV_DONTNEED), -1) << "madvise failed";
1044 std::fill(page_end, mem_end, 0);
1045 }
1046}
1047
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -08001048void MemMap::AlignBy(size_t size) {
1049 CHECK_EQ(begin_, base_begin_) << "Unsupported";
1050 CHECK_EQ(size_, base_size_) << "Unsupported";
1051 CHECK_GT(size, static_cast<size_t>(kPageSize));
1052 CHECK_ALIGNED(size, kPageSize);
1053 if (IsAlignedParam(reinterpret_cast<uintptr_t>(base_begin_), size) &&
1054 IsAlignedParam(base_size_, size)) {
1055 // Already aligned.
1056 return;
1057 }
1058 uint8_t* base_begin = reinterpret_cast<uint8_t*>(base_begin_);
1059 uint8_t* base_end = base_begin + base_size_;
1060 uint8_t* aligned_base_begin = AlignUp(base_begin, size);
1061 uint8_t* aligned_base_end = AlignDown(base_end, size);
1062 CHECK_LE(base_begin, aligned_base_begin);
1063 CHECK_LE(aligned_base_end, base_end);
1064 size_t aligned_base_size = aligned_base_end - aligned_base_begin;
1065 CHECK_LT(aligned_base_begin, aligned_base_end)
1066 << "base_begin = " << reinterpret_cast<void*>(base_begin)
1067 << " base_end = " << reinterpret_cast<void*>(base_end);
1068 CHECK_GE(aligned_base_size, size);
1069 // Unmap the unaligned parts.
1070 if (base_begin < aligned_base_begin) {
1071 MEMORY_TOOL_MAKE_UNDEFINED(base_begin, aligned_base_begin - base_begin);
1072 CHECK_EQ(munmap(base_begin, aligned_base_begin - base_begin), 0)
1073 << "base_begin=" << reinterpret_cast<void*>(base_begin)
1074 << " aligned_base_begin=" << reinterpret_cast<void*>(aligned_base_begin);
1075 }
1076 if (aligned_base_end < base_end) {
1077 MEMORY_TOOL_MAKE_UNDEFINED(aligned_base_end, base_end - aligned_base_end);
1078 CHECK_EQ(munmap(aligned_base_end, base_end - aligned_base_end), 0)
1079 << "base_end=" << reinterpret_cast<void*>(base_end)
1080 << " aligned_base_end=" << reinterpret_cast<void*>(aligned_base_end);
1081 }
1082 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
1083 base_begin_ = aligned_base_begin;
1084 base_size_ = aligned_base_size;
1085 begin_ = aligned_base_begin;
1086 size_ = aligned_base_size;
Andreas Gampe0dfc3152017-04-24 07:58:06 -07001087 DCHECK(gMaps != nullptr);
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -08001088 if (base_begin < aligned_base_begin) {
Andreas Gampe0dfc3152017-04-24 07:58:06 -07001089 auto it = gMaps->find(base_begin);
1090 CHECK(it != gMaps->end()) << "MemMap not found";
1091 gMaps->erase(it);
1092 gMaps->insert(std::make_pair(base_begin_, this));
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -08001093 }
1094}
1095
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001096} // namespace art