blob: 859269a5217ca7a3e7992b9cba5a3c8830827488 [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"
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -070018#include "thread-inl.h"
Brian Carlstrom27ec9612011-09-19 20:20:38 -070019
Ian Rogersdebeb3a2014-01-23 16:54:52 -080020#include <inttypes.h>
Christopher Ferris943af7d2014-01-16 12:41:46 -080021#include <backtrace/BacktraceMap.h>
Ian Rogers700a4022014-05-19 16:49:03 -070022#include <memory>
Elliott Hughesecd3a6f2012-06-06 18:16:37 -070023
Andreas Gamped8f26db2014-05-19 17:01:13 -070024// See CreateStartPos below.
25#ifdef __BIONIC__
26#include <sys/auxv.h>
27#endif
28
Elliott Hughese222ee02012-12-13 14:41:43 -080029#include "base/stringprintf.h"
30#include "ScopedFd.h"
31#include "utils.h"
32
Elliott Hughes6c9c06d2011-11-07 16:43:47 -080033#define USE_ASHMEM 1
34
35#ifdef USE_ASHMEM
36#include <cutils/ashmem.h>
37#endif
38
Brian Carlstrom27ec9612011-09-19 20:20:38 -070039namespace art {
40
Christopher Ferris943af7d2014-01-16 12:41:46 -080041static std::ostream& operator<<(
42 std::ostream& os,
43 std::pair<BacktraceMap::const_iterator, BacktraceMap::const_iterator> iters) {
44 for (BacktraceMap::const_iterator it = iters.first; it != iters.second; ++it) {
45 os << StringPrintf("0x%08x-0x%08x %c%c%c %s\n",
46 static_cast<uint32_t>(it->start),
47 static_cast<uint32_t>(it->end),
48 (it->flags & PROT_READ) ? 'r' : '-',
49 (it->flags & PROT_WRITE) ? 'w' : '-',
50 (it->flags & PROT_EXEC) ? 'x' : '-', it->name.c_str());
Elliott Hughesecd3a6f2012-06-06 18:16:37 -070051 }
52 return os;
Brian Carlstrom27ec9612011-09-19 20:20:38 -070053}
54
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -070055std::ostream& operator<<(std::ostream& os, const std::multimap<void*, MemMap*>& mem_maps) {
56 os << "MemMap:" << std::endl;
57 for (auto it = mem_maps.begin(); it != mem_maps.end(); ++it) {
58 void* base = it->first;
59 MemMap* map = it->second;
60 CHECK_EQ(base, map->BaseBegin());
61 os << *map << std::endl;
62 }
63 return os;
64}
65
66std::multimap<void*, MemMap*> MemMap::maps_;
67
Stuart Monteith8dba5aa2014-03-12 12:44:01 +000068#if defined(__LP64__) && !defined(__x86_64__)
Andreas Gamped8f26db2014-05-19 17:01:13 -070069// Handling mem_map in 32b address range for 64b architectures that do not support MAP_32BIT.
70
71// The regular start of memory allocations. The first 64KB is protected by SELinux.
Andreas Gampe6bd621a2014-05-16 17:28:58 -070072static constexpr uintptr_t LOW_MEM_START = 64 * KB;
Andreas Gampe7104cbf2014-03-21 11:44:43 -070073
Andreas Gamped8f26db2014-05-19 17:01:13 -070074// Generate random starting position.
75// To not interfere with image position, take the image's address and only place it below. Current
76// formula (sketch):
77//
78// ART_BASE_ADDR = 0001XXXXXXXXXXXXXXX
79// ----------------------------------------
80// = 0000111111111111111
81// & ~(kPageSize - 1) =~0000000000000001111
82// ----------------------------------------
83// mask = 0000111111111110000
84// & random data = YYYYYYYYYYYYYYYYYYY
85// -----------------------------------
86// tmp = 0000YYYYYYYYYYY0000
87// + LOW_MEM_START = 0000000000001000000
88// --------------------------------------
89// start
90//
91// getauxval as an entropy source is exposed in Bionic, but not in glibc before 2.16. When we
92// do not have Bionic, simply start with LOW_MEM_START.
93
94// Function is standalone so it can be tested somewhat in mem_map_test.cc.
95#ifdef __BIONIC__
96uintptr_t CreateStartPos(uint64_t input) {
97 CHECK_NE(0, ART_BASE_ADDRESS);
98
99 // Start with all bits below highest bit in ART_BASE_ADDRESS.
100 constexpr size_t leading_zeros = CLZ(static_cast<uint32_t>(ART_BASE_ADDRESS));
101 constexpr uintptr_t mask_ones = (1 << (31 - leading_zeros)) - 1;
102
103 // Lowest (usually 12) bits are not used, as aligned by page size.
104 constexpr uintptr_t mask = mask_ones & ~(kPageSize - 1);
105
106 // Mask input data.
107 return (input & mask) + LOW_MEM_START;
108}
109#endif
110
111static uintptr_t GenerateNextMemPos() {
112#ifdef __BIONIC__
113 uint8_t* random_data = reinterpret_cast<uint8_t*>(getauxval(AT_RANDOM));
114 // The lower 8B are taken for the stack guard. Use the upper 8B (with mask).
115 return CreateStartPos(*reinterpret_cast<uintptr_t*>(random_data + 8));
116#else
117 // No auxv on host, see above.
118 return LOW_MEM_START;
119#endif
120}
121
122// Initialize linear scan to random position.
123uintptr_t MemMap::next_mem_pos_ = GenerateNextMemPos();
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000124#endif
125
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700126static bool CheckMapRequest(byte* expected_ptr, void* actual_ptr, size_t byte_count,
127 std::ostringstream* error_msg) {
128 // Handled first by caller for more specific error messages.
129 CHECK(actual_ptr != MAP_FAILED);
130
131 if (expected_ptr == nullptr) {
132 return true;
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700133 }
Elliott Hughesecd3a6f2012-06-06 18:16:37 -0700134
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700135 if (expected_ptr == actual_ptr) {
136 return true;
137 }
138
139 // We asked for an address but didn't get what we wanted, all paths below here should fail.
140 int result = munmap(actual_ptr, byte_count);
141 if (result == -1) {
142 PLOG(WARNING) << StringPrintf("munmap(%p, %zd) failed", actual_ptr, byte_count);
143 }
144
145 uintptr_t actual = reinterpret_cast<uintptr_t>(actual_ptr);
146 uintptr_t expected = reinterpret_cast<uintptr_t>(expected_ptr);
147 uintptr_t limit = expected + byte_count;
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700148
Ian Rogers700a4022014-05-19 16:49:03 -0700149 std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(getpid()));
Christopher Ferriscaf22ac2014-01-27 18:32:14 -0800150 if (!map->Build()) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700151 *error_msg << StringPrintf("Failed to build process map to determine why mmap returned "
152 "0x%08" PRIxPTR " instead of 0x%08" PRIxPTR, actual, expected);
153
154 return false;
Christopher Ferris943af7d2014-01-16 12:41:46 -0800155 }
Christopher Ferriscaf22ac2014-01-27 18:32:14 -0800156 for (BacktraceMap::const_iterator it = map->begin(); it != map->end(); ++it) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700157 if ((expected >= it->start && expected < it->end) // start of new within old
158 || (limit > it->start && limit < it->end) // end of new within old
159 || (expected <= it->start && limit > it->end)) { // start/end of new includes all of old
160 *error_msg
161 << StringPrintf("Requested region 0x%08" PRIxPTR "-0x%08" PRIxPTR " overlaps with "
162 "existing map 0x%08" PRIxPTR "-0x%08" PRIxPTR " (%s)\n",
163 expected, limit,
164 static_cast<uintptr_t>(it->start), static_cast<uintptr_t>(it->end),
165 it->name.c_str())
166 << std::make_pair(it, map->end());
167 return false;
168 }
Elliott Hughes96970cd2012-03-13 15:46:31 -0700169 }
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700170 *error_msg << StringPrintf("Failed to mmap at expected address, mapped at "
171 "0x%08" PRIxPTR " instead of 0x%08" PRIxPTR, actual, expected);
172 return false;
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700173}
174
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700175MemMap* MemMap::MapAnonymous(const char* name, byte* expected, size_t byte_count, int prot,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800176 bool low_4gb, std::string* error_msg) {
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700177 if (byte_count == 0) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700178 return new MemMap(name, nullptr, 0, nullptr, 0, prot);
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700179 }
Elliott Hughesecd3a6f2012-06-06 18:16:37 -0700180 size_t page_aligned_byte_count = RoundUp(byte_count, kPageSize);
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800181
182#ifdef USE_ASHMEM
Ian Rogersa40307e2013-02-22 11:32:44 -0800183 // android_os_Debug.cpp read_mapinfo assumes all ashmem regions associated with the VM are
184 // prefixed "dalvik-".
185 std::string debug_friendly_name("dalvik-");
186 debug_friendly_name += name;
187 ScopedFd fd(ashmem_create_region(debug_friendly_name.c_str(), page_aligned_byte_count));
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800188 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700189 *error_msg = StringPrintf("ashmem_create_region failed for '%s': %s", name, strerror(errno));
190 return nullptr;
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800191 }
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700192 int flags = MAP_PRIVATE;
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800193#else
194 ScopedFd fd(-1);
195 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
196#endif
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000197
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700198 // We need to store and potentially set an error number for pretty printing of errors
199 int saved_errno = 0;
200
Qiming Shi84d49cc2014-04-24 15:38:41 +0800201#ifdef __LP64__
202 // When requesting low_4g memory and having an expectation, the requested range should fit into
203 // 4GB.
204 if (low_4gb && (
205 // Start out of bounds.
206 (reinterpret_cast<uintptr_t>(expected) >> 32) != 0 ||
207 // End out of bounds. For simplicity, this will fail for the last page of memory.
208 (reinterpret_cast<uintptr_t>(expected + page_aligned_byte_count) >> 32) != 0)) {
209 *error_msg = StringPrintf("The requested address space (%p, %p) cannot fit in low_4gb",
210 expected, expected + page_aligned_byte_count);
211 return nullptr;
212 }
213#endif
214
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000215 // TODO:
216 // A page allocator would be a useful abstraction here, as
217 // 1) It is doubtful that MAP_32BIT on x86_64 is doing the right job for us
218 // 2) The linear scheme, even with simple saving of the last known position, is very crude
219#if defined(__LP64__) && !defined(__x86_64__)
220 // MAP_32BIT only available on x86_64.
221 void* actual = MAP_FAILED;
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000222 if (low_4gb && expected == nullptr) {
223 flags |= MAP_FIXED;
224
Andreas Gampe7104cbf2014-03-21 11:44:43 -0700225 bool first_run = true;
226
Andreas Gampe71a3eba2014-03-17 12:57:08 -0700227 for (uintptr_t ptr = next_mem_pos_; ptr < 4 * GB; ptr += kPageSize) {
Andreas Gampe7104cbf2014-03-21 11:44:43 -0700228 if (4U * GB - ptr < page_aligned_byte_count) {
229 // Not enough memory until 4GB.
230 if (first_run) {
231 // Try another time from the bottom;
Andreas Gampe9de65ff2014-03-21 17:25:57 -0700232 ptr = LOW_MEM_START - kPageSize;
Andreas Gampe7104cbf2014-03-21 11:44:43 -0700233 first_run = false;
234 continue;
235 } else {
236 // Second try failed.
237 break;
238 }
239 }
240
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000241 uintptr_t tail_ptr;
242
243 // Check pages are free.
244 bool safe = true;
245 for (tail_ptr = ptr; tail_ptr < ptr + page_aligned_byte_count; tail_ptr += kPageSize) {
246 if (msync(reinterpret_cast<void*>(tail_ptr), kPageSize, 0) == 0) {
247 safe = false;
248 break;
249 } else {
250 DCHECK_EQ(errno, ENOMEM);
251 }
252 }
253
254 next_mem_pos_ = tail_ptr; // update early, as we break out when we found and mapped a region
255
256 if (safe == true) {
257 actual = mmap(reinterpret_cast<void*>(ptr), page_aligned_byte_count, prot, flags, fd.get(),
258 0);
259 if (actual != MAP_FAILED) {
260 break;
261 }
262 } else {
263 // Skip over last page.
264 ptr = tail_ptr;
265 }
266 }
267
268 if (actual == MAP_FAILED) {
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700269 LOG(ERROR) << "Could not find contiguous low-memory space.";
270 saved_errno = ENOMEM;
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000271 }
272 } else {
273 actual = mmap(expected, page_aligned_byte_count, prot, flags, fd.get(), 0);
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700274 saved_errno = errno;
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000275 }
276
277#else
278#ifdef __x86_64__
Qiming Shi84d49cc2014-04-24 15:38:41 +0800279 if (low_4gb && expected == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800280 flags |= MAP_32BIT;
281 }
282#endif
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700283
284 void* actual = mmap(expected, page_aligned_byte_count, prot, flags, fd.get(), 0);
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700285 saved_errno = errno;
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000286#endif
287
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700288 if (actual == MAP_FAILED) {
jeffhao8161c032012-10-31 15:50:00 -0700289 std::string maps;
290 ReadFileToString("/proc/self/maps", &maps);
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700291
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700292 *error_msg = StringPrintf("Failed anonymous mmap(%p, %zd, 0x%x, 0x%x, %d, 0): %s\n%s",
293 expected, page_aligned_byte_count, prot, flags, fd.get(),
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700294 strerror(saved_errno), maps.c_str());
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700295 return nullptr;
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700296 }
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700297 std::ostringstream check_map_request_error_msg;
298 if (!CheckMapRequest(expected, actual, page_aligned_byte_count, &check_map_request_error_msg)) {
299 *error_msg = check_map_request_error_msg.str();
300 return nullptr;
301 }
302 return new MemMap(name, reinterpret_cast<byte*>(actual), byte_count, actual,
303 page_aligned_byte_count, prot);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700304}
305
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700306MemMap* MemMap::MapFileAtAddress(byte* expected, size_t byte_count, int prot, int flags, int fd,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700307 off_t start, bool reuse, const char* filename,
308 std::string* error_msg) {
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700309 CHECK_NE(0, prot);
310 CHECK_NE(0, flags & (MAP_SHARED | MAP_PRIVATE));
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700311 if (reuse) {
312 // reuse means it is okay that it overlaps an existing page mapping.
313 // Only use this if you actually made the page reservation yourself.
314 CHECK(expected != nullptr);
315 flags |= MAP_FIXED;
316 } else {
317 CHECK_EQ(0, flags & MAP_FIXED);
318 }
319
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700320 if (byte_count == 0) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700321 return new MemMap(filename, nullptr, 0, nullptr, 0, prot);
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700322 }
Ian Rogersf8adc602013-04-18 17:06:19 -0700323 // Adjust 'offset' to be page-aligned as required by mmap.
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700324 int page_offset = start % kPageSize;
325 off_t page_aligned_offset = start - page_offset;
Ian Rogersf8adc602013-04-18 17:06:19 -0700326 // Adjust 'byte_count' to be page-aligned as we will map this anyway.
Elliott Hughesecd3a6f2012-06-06 18:16:37 -0700327 size_t page_aligned_byte_count = RoundUp(byte_count + page_offset, kPageSize);
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700328 // The 'expected' is modified (if specified, ie non-null) to be page aligned to the file but not
329 // necessarily to virtual memory. mmap will page align 'expected' for us.
330 byte* page_aligned_expected = (expected == nullptr) ? nullptr : (expected - page_offset);
331
332 byte* actual = reinterpret_cast<byte*>(mmap(page_aligned_expected,
Elliott Hughesecd3a6f2012-06-06 18:16:37 -0700333 page_aligned_byte_count,
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700334 prot,
335 flags,
336 fd,
337 page_aligned_offset));
338 if (actual == MAP_FAILED) {
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700339 auto saved_errno = errno;
340
jeffhao8161c032012-10-31 15:50:00 -0700341 std::string maps;
342 ReadFileToString("/proc/self/maps", &maps);
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700343
Mathieu Chartierc7cb1902014-03-05 14:41:03 -0800344 *error_msg = StringPrintf("mmap(%p, %zd, 0x%x, 0x%x, %d, %" PRId64
345 ") of file '%s' failed: %s\n%s",
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700346 page_aligned_expected, page_aligned_byte_count, prot, flags, fd,
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700347 static_cast<int64_t>(page_aligned_offset), filename,
348 strerror(saved_errno), maps.c_str());
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700349 return nullptr;
350 }
351 std::ostringstream check_map_request_error_msg;
352 if (!CheckMapRequest(expected, actual, page_aligned_byte_count, &check_map_request_error_msg)) {
353 *error_msg = check_map_request_error_msg.str();
354 return nullptr;
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700355 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800356 return new MemMap(filename, actual + page_offset, byte_count, actual, page_aligned_byte_count,
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700357 prot);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700358}
359
360MemMap::~MemMap() {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700361 if (base_begin_ == nullptr && base_size_ == 0) {
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700362 return;
363 }
Ian Rogers30fab402012-01-23 15:43:46 -0800364 int result = munmap(base_begin_, base_size_);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700365 if (result == -1) {
366 PLOG(FATAL) << "munmap failed";
367 }
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700368
369 // Remove it from maps_.
370 MutexLock mu(Thread::Current(), *Locks::mem_maps_lock_);
371 bool found = false;
372 for (auto it = maps_.lower_bound(base_begin_), end = maps_.end();
373 it != end && it->first == base_begin_; ++it) {
374 if (it->second == this) {
375 found = true;
376 maps_.erase(it);
377 break;
378 }
379 }
380 CHECK(found) << "MemMap not found";
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700381}
382
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700383MemMap::MemMap(const std::string& name, byte* begin, size_t size, void* base_begin,
384 size_t base_size, int prot)
385 : name_(name), begin_(begin), size_(size), base_begin_(base_begin), base_size_(base_size),
386 prot_(prot) {
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700387 if (size_ == 0) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700388 CHECK(begin_ == nullptr);
389 CHECK(base_begin_ == nullptr);
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700390 CHECK_EQ(base_size_, 0U);
391 } else {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700392 CHECK(begin_ != nullptr);
393 CHECK(base_begin_ != nullptr);
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700394 CHECK_NE(base_size_, 0U);
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700395
396 // Add it to maps_.
397 MutexLock mu(Thread::Current(), *Locks::mem_maps_lock_);
398 maps_.insert(std::pair<void*, MemMap*>(base_begin_, this));
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700399 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700400};
401
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700402MemMap* MemMap::RemapAtEnd(byte* new_end, const char* tail_name, int tail_prot,
403 std::string* error_msg) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700404 DCHECK_GE(new_end, Begin());
405 DCHECK_LE(new_end, End());
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700406 DCHECK_LE(begin_ + size_, reinterpret_cast<byte*>(base_begin_) + base_size_);
407 DCHECK(IsAligned<kPageSize>(begin_));
408 DCHECK(IsAligned<kPageSize>(base_begin_));
409 DCHECK(IsAligned<kPageSize>(reinterpret_cast<byte*>(base_begin_) + base_size_));
410 DCHECK(IsAligned<kPageSize>(new_end));
411 byte* old_end = begin_ + size_;
412 byte* old_base_end = reinterpret_cast<byte*>(base_begin_) + base_size_;
413 byte* new_base_end = new_end;
414 DCHECK_LE(new_base_end, old_base_end);
415 if (new_base_end == old_base_end) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700416 return new MemMap(tail_name, nullptr, 0, nullptr, 0, tail_prot);
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700417 }
418 size_ = new_end - reinterpret_cast<byte*>(begin_);
419 base_size_ = new_base_end - reinterpret_cast<byte*>(base_begin_);
420 DCHECK_LE(begin_ + size_, reinterpret_cast<byte*>(base_begin_) + base_size_);
421 size_t tail_size = old_end - new_end;
422 byte* tail_base_begin = new_base_end;
423 size_t tail_base_size = old_base_end - new_base_end;
424 DCHECK_EQ(tail_base_begin + tail_base_size, old_base_end);
425 DCHECK(IsAligned<kPageSize>(tail_base_size));
426
427#ifdef USE_ASHMEM
428 // android_os_Debug.cpp read_mapinfo assumes all ashmem regions associated with the VM are
429 // prefixed "dalvik-".
430 std::string debug_friendly_name("dalvik-");
431 debug_friendly_name += tail_name;
432 ScopedFd fd(ashmem_create_region(debug_friendly_name.c_str(), tail_base_size));
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000433 int flags = MAP_PRIVATE | MAP_FIXED;
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700434 if (fd.get() == -1) {
435 *error_msg = StringPrintf("ashmem_create_region failed for '%s': %s",
436 tail_name, strerror(errno));
437 return nullptr;
438 }
439#else
440 ScopedFd fd(-1);
441 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
442#endif
443
444 // Unmap/map the tail region.
445 int result = munmap(tail_base_begin, tail_base_size);
446 if (result == -1) {
447 std::string maps;
448 ReadFileToString("/proc/self/maps", &maps);
449 *error_msg = StringPrintf("munmap(%p, %zd) failed for '%s'\n%s",
450 tail_base_begin, tail_base_size, name_.c_str(),
451 maps.c_str());
452 return nullptr;
453 }
454 // Don't cause memory allocation between the munmap and the mmap
455 // calls. Otherwise, libc (or something else) might take this memory
456 // region. Note this isn't perfect as there's no way to prevent
457 // other threads to try to take this memory region here.
458 byte* actual = reinterpret_cast<byte*>(mmap(tail_base_begin, tail_base_size, tail_prot,
459 flags, fd.get(), 0));
460 if (actual == MAP_FAILED) {
461 std::string maps;
462 ReadFileToString("/proc/self/maps", &maps);
Mathieu Chartierc7cb1902014-03-05 14:41:03 -0800463 *error_msg = StringPrintf("anonymous mmap(%p, %zd, 0x%x, 0x%x, %d, 0) failed\n%s",
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700464 tail_base_begin, tail_base_size, tail_prot, flags, fd.get(),
465 maps.c_str());
466 return nullptr;
467 }
468 return new MemMap(tail_name, actual, tail_size, actual, tail_base_size, tail_prot);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700469}
Logan Chiend88fa262012-06-06 15:23:32 +0800470
471bool MemMap::Protect(int prot) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700472 if (base_begin_ == nullptr && base_size_ == 0) {
Ian Rogers1c849e52012-06-28 14:00:33 -0700473 prot_ = prot;
Logan Chiend88fa262012-06-06 15:23:32 +0800474 return true;
475 }
476
477 if (mprotect(base_begin_, base_size_, prot) == 0) {
Ian Rogers1c849e52012-06-28 14:00:33 -0700478 prot_ = prot;
Logan Chiend88fa262012-06-06 15:23:32 +0800479 return true;
480 }
481
Shih-wei Liaoa060ed92012-06-07 09:25:28 -0700482 PLOG(ERROR) << "mprotect(" << reinterpret_cast<void*>(base_begin_) << ", " << base_size_ << ", "
483 << prot << ") failed";
Logan Chiend88fa262012-06-06 15:23:32 +0800484 return false;
485}
486
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700487bool MemMap::CheckNoGaps(MemMap* begin_map, MemMap* end_map) {
488 MutexLock mu(Thread::Current(), *Locks::mem_maps_lock_);
489 CHECK(begin_map != nullptr);
490 CHECK(end_map != nullptr);
491 CHECK(HasMemMap(begin_map));
492 CHECK(HasMemMap(end_map));
493 CHECK_LE(begin_map->BaseBegin(), end_map->BaseBegin());
494 MemMap* map = begin_map;
495 while (map->BaseBegin() != end_map->BaseBegin()) {
496 MemMap* next_map = GetLargestMemMapAt(map->BaseEnd());
497 if (next_map == nullptr) {
498 // Found a gap.
499 return false;
500 }
501 map = next_map;
502 }
503 return true;
504}
505
506void MemMap::DumpMaps(std::ostream& os) {
507 DumpMaps(os, maps_);
508}
509
510void MemMap::DumpMaps(std::ostream& os, const std::multimap<void*, MemMap*>& mem_maps) {
511 MutexLock mu(Thread::Current(), *Locks::mem_maps_lock_);
512 DumpMapsLocked(os, mem_maps);
513}
514
515void MemMap::DumpMapsLocked(std::ostream& os, const std::multimap<void*, MemMap*>& mem_maps) {
516 os << mem_maps;
517}
518
519bool MemMap::HasMemMap(MemMap* map) {
520 void* base_begin = map->BaseBegin();
521 for (auto it = maps_.lower_bound(base_begin), end = maps_.end();
522 it != end && it->first == base_begin; ++it) {
523 if (it->second == map) {
524 return true;
525 }
526 }
527 return false;
528}
529
530MemMap* MemMap::GetLargestMemMapAt(void* address) {
531 size_t largest_size = 0;
532 MemMap* largest_map = nullptr;
533 for (auto it = maps_.lower_bound(address), end = maps_.end();
534 it != end && it->first == address; ++it) {
535 MemMap* map = it->second;
536 CHECK(map != nullptr);
537 if (largest_size < map->BaseSize()) {
538 largest_size = map->BaseSize();
539 largest_map = map;
540 }
541 }
542 return largest_map;
543}
544
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800545std::ostream& operator<<(std::ostream& os, const MemMap& mem_map) {
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700546 os << StringPrintf("[MemMap: %p-%p prot=0x%x %s]",
547 mem_map.BaseBegin(), mem_map.BaseEnd(), mem_map.GetProtect(),
548 mem_map.GetName().c_str());
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800549 return os;
550}
551
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700552} // namespace art