blob: aa07f1c6effae69ab12e31bb2fb0865e87077f1f [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>
David Sehr10db8fe2018-07-18 11:01:20 -070021#if !defined(ANDROID_OS) && !defined(__Fuchsia__) && !defined(_WIN32)
Andreas Gampe0dfc3152017-04-24 07:58:06 -070022#include <sys/resource.h>
23#endif
Ian Rogersc7dd2952014-10-21 23:31:19 -070024
Joel Fernandes (Google)92597a82018-08-17 16:19:19 -070025#if defined(__linux__)
26#include <sys/prctl.h>
27#endif
28
Andreas Gampe3b7dc352017-06-06 20:02:03 -070029#include <map>
Ian Rogers700a4022014-05-19 16:49:03 -070030#include <memory>
Ian Rogersc7dd2952014-10-21 23:31:19 -070031#include <sstream>
Elliott Hughesecd3a6f2012-06-06 18:16:37 -070032
Andreas Gampe46ee31b2016-12-14 10:11:49 -080033#include "android-base/stringprintf.h"
Andreas Gampe0dfc3152017-04-24 07:58:06 -070034#include "android-base/unique_fd.h"
Steve Austin882ed6b2018-06-08 11:40:38 -070035
David Sehr1979c642018-04-26 14:41:18 -070036#include "allocator.h"
37#include "bit_utils.h"
38#include "globals.h"
39#include "logging.h" // For VLOG_IS_ON.
40#include "memory_tool.h"
David Sehr10db8fe2018-07-18 11:01:20 -070041#include "mman.h" // For the PROT_* and MAP_* constants.
David Sehr1979c642018-04-26 14:41:18 -070042#include "utils.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080043
Ian Rogersd6b68652014-06-23 14:07:03 -070044#ifndef MAP_ANONYMOUS
45#define MAP_ANONYMOUS MAP_ANON
46#endif
47
Brian Carlstrom27ec9612011-09-19 20:20:38 -070048namespace art {
49
Andreas Gampe46ee31b2016-12-14 10:11:49 -080050using android::base::StringPrintf;
Andreas Gampe0dfc3152017-04-24 07:58:06 -070051using android::base::unique_fd;
52
Andreas Gampe3b7dc352017-06-06 20:02:03 -070053template<class Key, class T, AllocatorTag kTag, class Compare = std::less<Key>>
54using AllocationTrackingMultiMap =
55 std::multimap<Key, T, Compare, TrackingAllocator<std::pair<const Key, T>, kTag>>;
56
Andreas Gampe0dfc3152017-04-24 07:58:06 -070057using Maps = AllocationTrackingMultiMap<void*, MemMap*, kAllocatorTagMaps>;
58
59// All the non-empty MemMaps. Use a multimap as we do a reserve-and-divide (eg ElfMap::Load()).
60static Maps* gMaps GUARDED_BY(MemMap::GetMemMapsLock()) = nullptr;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080061
Joel Fernandes (Google)92597a82018-08-17 16:19:19 -070062// A map containing unique strings used for indentifying anonymous mappings
63static std::map<std::string, int> debugStrMap GUARDED_BY(MemMap::GetMemMapsLock());
64
Vladimir Markoc34bebf2018-08-16 16:12:49 +010065// Retrieve iterator to a `gMaps` entry that is known to exist.
66Maps::iterator GetGMapsEntry(const MemMap& map) REQUIRES(MemMap::GetMemMapsLock()) {
67 DCHECK(map.IsValid());
68 DCHECK(gMaps != nullptr);
69 for (auto it = gMaps->lower_bound(map.BaseBegin()), end = gMaps->end();
70 it != end && it->first == map.BaseBegin();
71 ++it) {
72 if (it->second == &map) {
73 return it;
74 }
75 }
76 LOG(FATAL) << "MemMap not found";
77 UNREACHABLE();
78}
79
Andreas Gampe0dfc3152017-04-24 07:58:06 -070080std::ostream& operator<<(std::ostream& os, const Maps& mem_maps) {
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -070081 os << "MemMap:" << std::endl;
82 for (auto it = mem_maps.begin(); it != mem_maps.end(); ++it) {
83 void* base = it->first;
84 MemMap* map = it->second;
85 CHECK_EQ(base, map->BaseBegin());
86 os << *map << std::endl;
87 }
88 return os;
89}
90
David Sehr1b14fb82017-02-01 10:42:11 -080091std::mutex* MemMap::mem_maps_lock_ = nullptr;
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -070092
Ian Rogersc3ccc102014-06-25 11:52:14 -070093#if USE_ART_LOW_4G_ALLOCATOR
Andreas Gamped8f26db2014-05-19 17:01:13 -070094// Handling mem_map in 32b address range for 64b architectures that do not support MAP_32BIT.
95
96// The regular start of memory allocations. The first 64KB is protected by SELinux.
Andreas Gampe6bd621a2014-05-16 17:28:58 -070097static constexpr uintptr_t LOW_MEM_START = 64 * KB;
Andreas Gampe7104cbf2014-03-21 11:44:43 -070098
Andreas Gamped8f26db2014-05-19 17:01:13 -070099// Generate random starting position.
100// To not interfere with image position, take the image's address and only place it below. Current
101// formula (sketch):
102//
103// ART_BASE_ADDR = 0001XXXXXXXXXXXXXXX
104// ----------------------------------------
105// = 0000111111111111111
106// & ~(kPageSize - 1) =~0000000000000001111
107// ----------------------------------------
108// mask = 0000111111111110000
109// & random data = YYYYYYYYYYYYYYYYYYY
110// -----------------------------------
111// tmp = 0000YYYYYYYYYYY0000
112// + LOW_MEM_START = 0000000000001000000
113// --------------------------------------
114// start
115//
Josh Gao0389cd52015-09-16 16:27:00 -0700116// arc4random as an entropy source is exposed in Bionic, but not in glibc. When we
Andreas Gamped8f26db2014-05-19 17:01:13 -0700117// do not have Bionic, simply start with LOW_MEM_START.
118
119// Function is standalone so it can be tested somewhat in mem_map_test.cc.
120#ifdef __BIONIC__
121uintptr_t CreateStartPos(uint64_t input) {
122 CHECK_NE(0, ART_BASE_ADDRESS);
123
124 // Start with all bits below highest bit in ART_BASE_ADDRESS.
125 constexpr size_t leading_zeros = CLZ(static_cast<uint32_t>(ART_BASE_ADDRESS));
126 constexpr uintptr_t mask_ones = (1 << (31 - leading_zeros)) - 1;
127
128 // Lowest (usually 12) bits are not used, as aligned by page size.
129 constexpr uintptr_t mask = mask_ones & ~(kPageSize - 1);
130
131 // Mask input data.
132 return (input & mask) + LOW_MEM_START;
133}
134#endif
135
136static uintptr_t GenerateNextMemPos() {
137#ifdef __BIONIC__
Josh Gao0389cd52015-09-16 16:27:00 -0700138 uint64_t random_data;
139 arc4random_buf(&random_data, sizeof(random_data));
140 return CreateStartPos(random_data);
Andreas Gamped8f26db2014-05-19 17:01:13 -0700141#else
Josh Gao0389cd52015-09-16 16:27:00 -0700142 // No arc4random on host, see above.
Andreas Gamped8f26db2014-05-19 17:01:13 -0700143 return LOW_MEM_START;
144#endif
145}
146
147// Initialize linear scan to random position.
148uintptr_t MemMap::next_mem_pos_ = GenerateNextMemPos();
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000149#endif
150
Mathieu Chartier24a0fc82015-10-13 16:38:52 -0700151// Return true if the address range is contained in a single memory map by either reading
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700152// the gMaps variable or the /proc/self/map entry.
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700153bool MemMap::ContainedWithinExistingMap(uint8_t* ptr, size_t size, std::string* error_msg) {
Vladimir Marko5c42c292015-02-25 12:02:49 +0000154 uintptr_t begin = reinterpret_cast<uintptr_t>(ptr);
155 uintptr_t end = begin + size;
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700156
157 {
David Sehr1b14fb82017-02-01 10:42:11 -0800158 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700159 for (auto& pair : *gMaps) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700160 MemMap* const map = pair.second;
161 if (begin >= reinterpret_cast<uintptr_t>(map->Begin()) &&
162 end <= reinterpret_cast<uintptr_t>(map->End())) {
163 return true;
164 }
165 }
166 }
167
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800168 if (error_msg != nullptr) {
169 PrintFileToLog("/proc/self/maps", LogSeverity::ERROR);
170 *error_msg = StringPrintf("Requested region 0x%08" PRIxPTR "-0x%08" PRIxPTR " does not overlap "
171 "any existing map. See process maps in the log.", begin, end);
172 }
Jim_Guoa62a5882014-04-28 11:11:57 +0800173 return false;
174}
175
Jim_Guoa62a5882014-04-28 11:11:57 +0800176// CheckMapRequest to validate a non-MAP_FAILED mmap result based on
177// the expected value, calling munmap if validation fails, giving the
178// reason in error_msg.
179//
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700180// If the expected_ptr is null, nothing is checked beyond the fact
Jim_Guoa62a5882014-04-28 11:11:57 +0800181// that the actual_ptr is not MAP_FAILED. However, if expected_ptr is
182// non-null, we check that pointer is the actual_ptr == expected_ptr,
183// and if not, report in error_msg what the conflict mapping was if
184// found, or a generic error in other cases.
Steve Austin882ed6b2018-06-08 11:40:38 -0700185bool MemMap::CheckMapRequest(uint8_t* expected_ptr, void* actual_ptr, size_t byte_count,
Jim_Guoa62a5882014-04-28 11:11:57 +0800186 std::string* error_msg) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700187 // Handled first by caller for more specific error messages.
188 CHECK(actual_ptr != MAP_FAILED);
189
190 if (expected_ptr == nullptr) {
191 return true;
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700192 }
Elliott Hughesecd3a6f2012-06-06 18:16:37 -0700193
Jim_Guoa62a5882014-04-28 11:11:57 +0800194 uintptr_t actual = reinterpret_cast<uintptr_t>(actual_ptr);
195 uintptr_t expected = reinterpret_cast<uintptr_t>(expected_ptr);
Jim_Guoa62a5882014-04-28 11:11:57 +0800196
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700197 if (expected_ptr == actual_ptr) {
198 return true;
199 }
200
201 // We asked for an address but didn't get what we wanted, all paths below here should fail.
Steve Austin882ed6b2018-06-08 11:40:38 -0700202 int result = TargetMUnmap(actual_ptr, byte_count);
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700203 if (result == -1) {
204 PLOG(WARNING) << StringPrintf("munmap(%p, %zd) failed", actual_ptr, byte_count);
205 }
206
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800207 if (error_msg != nullptr) {
Mathieu Chartier83723ae2016-02-24 10:09:23 -0800208 // We call this here so that we can try and generate a full error
209 // message with the overlapping mapping. There's no guarantee that
210 // that there will be an overlap though, since
211 // - The kernel is not *required* to honor expected_ptr unless MAP_FIXED is
212 // true, even if there is no overlap
213 // - There might have been an overlap at the point of mmap, but the
214 // overlapping region has since been unmapped.
David Sehr2300b2d2018-05-10 14:20:10 -0700215
216 // Tell the client the mappings that were in place at the time.
217 if (kIsDebugBuild) {
218 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
219 }
220
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800221 std::ostringstream os;
222 os << StringPrintf("Failed to mmap at expected address, mapped at "
223 "0x%08" PRIxPTR " instead of 0x%08" PRIxPTR,
224 actual, expected);
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800225 *error_msg = os.str();
Christopher Ferris943af7d2014-01-16 12:41:46 -0800226 }
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700227 return false;
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700228}
229
Vladimir Markoc09cd052018-08-23 16:36:36 +0100230bool MemMap::CheckReservation(uint8_t* expected_ptr,
231 size_t byte_count,
232 const char* name,
233 const MemMap& reservation,
234 /*out*/std::string* error_msg) {
235 if (!reservation.IsValid()) {
236 *error_msg = StringPrintf("Invalid reservation for %s", name);
237 return false;
238 }
239 DCHECK_ALIGNED(reservation.Begin(), kPageSize);
240 if (reservation.Begin() != expected_ptr) {
241 *error_msg = StringPrintf("Bad image reservation start for %s: %p instead of %p",
242 name,
243 reservation.Begin(),
244 expected_ptr);
245 return false;
246 }
247 if (byte_count > reservation.Size()) {
248 *error_msg = StringPrintf("Insufficient reservation, required %zu, available %zu",
249 byte_count,
250 reservation.Size());
251 return false;
252 }
253 return true;
254}
255
256
Mathieu Chartier38c82212015-06-04 16:22:41 -0700257#if USE_ART_LOW_4G_ALLOCATOR
Steve Austin882ed6b2018-06-08 11:40:38 -0700258void* MemMap::TryMemMapLow4GB(void* ptr,
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800259 size_t page_aligned_byte_count,
260 int prot,
261 int flags,
262 int fd,
263 off_t offset) {
Steve Austin882ed6b2018-06-08 11:40:38 -0700264 void* actual = TargetMMap(ptr, page_aligned_byte_count, prot, flags, fd, offset);
Mathieu Chartier38c82212015-06-04 16:22:41 -0700265 if (actual != MAP_FAILED) {
266 // Since we didn't use MAP_FIXED the kernel may have mapped it somewhere not in the low
267 // 4GB. If this is the case, unmap and retry.
268 if (reinterpret_cast<uintptr_t>(actual) + page_aligned_byte_count >= 4 * GB) {
Steve Austin882ed6b2018-06-08 11:40:38 -0700269 TargetMUnmap(actual, page_aligned_byte_count);
Mathieu Chartier38c82212015-06-04 16:22:41 -0700270 actual = MAP_FAILED;
271 }
272 }
273 return actual;
274}
275#endif
276
Joel Fernandes (Google)92597a82018-08-17 16:19:19 -0700277void MemMap::SetDebugName(void* map_ptr, const char* name, size_t size) {
278 // Debug naming is only used for Android target builds. For Linux targets,
279 // we'll still call prctl but it wont do anything till we upstream the prctl.
280 if (kIsTargetFuchsia || !kIsTargetBuild) {
281 return;
282 }
283
284 // lock as std::map is not thread-safe
285 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
286
287 std::string debug_friendly_name("dalvik-");
288 debug_friendly_name += name;
289 auto it = debugStrMap.find(debug_friendly_name);
290
291 if (it == debugStrMap.end()) {
292 it = debugStrMap.insert(std::make_pair(std::move(debug_friendly_name), 1)).first;
293 }
294
295 DCHECK(it != debugStrMap.end());
296#if defined(PR_SET_VMA) && defined(__linux__)
297 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, map_ptr, size, it->first.c_str());
298#else
299 // Prevent variable unused compiler errors.
300 UNUSED(map_ptr, size);
301#endif
302}
303
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100304MemMap MemMap::MapAnonymous(const char* name,
305 uint8_t* addr,
306 size_t byte_count,
307 int prot,
308 bool low_4gb,
309 bool reuse,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100310 /*inout*/MemMap* reservation,
311 /*out*/std::string* error_msg,
Joel Fernandes (Google)92597a82018-08-17 16:19:19 -0700312 bool use_debug_name) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700313#ifndef __LP64__
314 UNUSED(low_4gb);
315#endif
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700316 if (byte_count == 0) {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100317 *error_msg = "Empty MemMap requested.";
318 return Invalid();
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700319 }
Elliott Hughesecd3a6f2012-06-06 18:16:37 -0700320 size_t page_aligned_byte_count = RoundUp(byte_count, kPageSize);
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800321
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800322 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
Vladimir Marko5c42c292015-02-25 12:02:49 +0000323 if (reuse) {
324 // reuse means it is okay that it overlaps an existing page mapping.
325 // Only use this if you actually made the page reservation yourself.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100326 CHECK(addr != nullptr);
Vladimir Markoc09cd052018-08-23 16:36:36 +0100327 DCHECK(reservation == nullptr);
Vladimir Marko5c42c292015-02-25 12:02:49 +0000328
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100329 DCHECK(ContainedWithinExistingMap(addr, byte_count, error_msg)) << *error_msg;
Vladimir Marko5c42c292015-02-25 12:02:49 +0000330 flags |= MAP_FIXED;
Vladimir Markoc09cd052018-08-23 16:36:36 +0100331 } else if (reservation != nullptr) {
332 CHECK(addr != nullptr);
333 if (!CheckReservation(addr, byte_count, name, *reservation, error_msg)) {
334 return MemMap::Invalid();
335 }
336 flags |= MAP_FIXED;
Vladimir Marko5c42c292015-02-25 12:02:49 +0000337 }
338
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700339 unique_fd fd;
340
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700341 // We need to store and potentially set an error number for pretty printing of errors
342 int saved_errno = 0;
343
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100344 void* actual = MapInternal(addr,
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800345 page_aligned_byte_count,
346 prot,
347 flags,
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700348 fd.get(),
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800349 0,
350 low_4gb);
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700351 saved_errno = errno;
Stuart Monteith8dba5aa2014-03-12 12:44:01 +0000352
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700353 if (actual == MAP_FAILED) {
Mathieu Chartier83723ae2016-02-24 10:09:23 -0800354 if (error_msg != nullptr) {
Andreas Gampe7fa55782016-06-15 17:45:01 -0700355 if (kIsDebugBuild || VLOG_IS_ON(oat)) {
356 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
357 }
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700358
Mathieu Chartier83723ae2016-02-24 10:09:23 -0800359 *error_msg = StringPrintf("Failed anonymous mmap(%p, %zd, 0x%x, 0x%x, %d, 0): %s. "
360 "See process maps in the log.",
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100361 addr,
Mathieu Chartier83723ae2016-02-24 10:09:23 -0800362 page_aligned_byte_count,
363 prot,
364 flags,
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700365 fd.get(),
Mathieu Chartier83723ae2016-02-24 10:09:23 -0800366 strerror(saved_errno));
367 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100368 return Invalid();
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700369 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100370 if (!CheckMapRequest(addr, actual, page_aligned_byte_count, error_msg)) {
371 return Invalid();
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700372 }
Joel Fernandes (Google)92597a82018-08-17 16:19:19 -0700373
374 if (use_debug_name) {
375 SetDebugName(actual, name, page_aligned_byte_count);
376 }
377
Vladimir Markoc09cd052018-08-23 16:36:36 +0100378 if (reservation != nullptr) {
379 // Re-mapping was successful, transfer the ownership of the memory to the new MemMap.
380 DCHECK_EQ(actual, reservation->Begin());
381 reservation->ReleaseReservedMemory(byte_count);
382 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100383 return MemMap(name,
384 reinterpret_cast<uint8_t*>(actual),
385 byte_count,
386 actual,
387 page_aligned_byte_count,
388 prot,
389 reuse);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700390}
391
Vladimir Marko07f78902020-07-27 11:35:12 +0000392MemMap MemMap::MapPlaceholder(const char* name, uint8_t* addr, size_t byte_count) {
David Srbecky1baabf02015-06-16 17:12:34 +0000393 if (byte_count == 0) {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100394 return Invalid();
David Srbecky1baabf02015-06-16 17:12:34 +0000395 }
396 const size_t page_aligned_byte_count = RoundUp(byte_count, kPageSize);
Andreas Gampe0de385f2018-10-11 11:11:13 -0700397 return MemMap(name, addr, byte_count, addr, page_aligned_byte_count, 0, /* reuse= */ true);
David Srbecky1baabf02015-06-16 17:12:34 +0000398}
399
Alex Lightca97ada2018-02-02 09:25:31 -0800400template<typename A, typename B>
401static ptrdiff_t PointerDiff(A* a, B* b) {
402 return static_cast<ptrdiff_t>(reinterpret_cast<intptr_t>(a) - reinterpret_cast<intptr_t>(b));
403}
404
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100405bool MemMap::ReplaceWith(MemMap* source, /*out*/std::string* error) {
Alex Lightca97ada2018-02-02 09:25:31 -0800406#if !HAVE_MREMAP_SYSCALL
Mathieu Chartier7bd3cbd2018-08-22 14:15:51 -0700407 UNUSED(source);
Alex Lightca97ada2018-02-02 09:25:31 -0800408 *error = "Cannot perform atomic replace because we are missing the required mremap syscall";
409 return false;
410#else // !HAVE_MREMAP_SYSCALL
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100411 CHECK(source != nullptr);
412 CHECK(source->IsValid());
Alex Lightca97ada2018-02-02 09:25:31 -0800413 if (!MemMap::kCanReplaceMapping) {
414 *error = "Unable to perform atomic replace due to runtime environment!";
415 return false;
416 }
Alex Lightca97ada2018-02-02 09:25:31 -0800417 // neither can be reuse.
418 if (source->reuse_ || reuse_) {
419 *error = "One or both mappings is not a real mmap!";
420 return false;
421 }
422 // TODO Support redzones.
423 if (source->redzone_size_ != 0 || redzone_size_ != 0) {
424 *error = "source and dest have different redzone sizes";
425 return false;
426 }
427 // Make sure they have the same offset from the actual mmap'd address
428 if (PointerDiff(BaseBegin(), Begin()) != PointerDiff(source->BaseBegin(), source->Begin())) {
429 *error =
430 "source starts at a different offset from the mmap. Cannot atomically replace mappings";
431 return false;
432 }
433 // mremap doesn't allow the final [start, end] to overlap with the initial [start, end] (it's like
434 // memcpy but the check is explicit and actually done).
435 if (source->BaseBegin() > BaseBegin() &&
436 reinterpret_cast<uint8_t*>(BaseBegin()) + source->BaseSize() >
437 reinterpret_cast<uint8_t*>(source->BaseBegin())) {
438 *error = "destination memory pages overlap with source memory pages";
439 return false;
440 }
441 // Change the protection to match the new location.
442 int old_prot = source->GetProtect();
443 if (!source->Protect(GetProtect())) {
444 *error = "Could not change protections for source to those required for dest.";
445 return false;
446 }
447
448 // Do the mremap.
449 void* res = mremap(/*old_address*/source->BaseBegin(),
450 /*old_size*/source->BaseSize(),
451 /*new_size*/source->BaseSize(),
452 /*flags*/MREMAP_MAYMOVE | MREMAP_FIXED,
453 /*new_address*/BaseBegin());
454 if (res == MAP_FAILED) {
455 int saved_errno = errno;
456 // Wasn't able to move mapping. Change the protection of source back to the original one and
457 // return.
458 source->Protect(old_prot);
459 *error = std::string("Failed to mremap source to dest. Error was ") + strerror(saved_errno);
460 return false;
461 }
462 CHECK(res == BaseBegin());
463
464 // The new base_size is all the pages of the 'source' plus any remaining dest pages. We will unmap
465 // them later.
466 size_t new_base_size = std::max(source->base_size_, base_size_);
467
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100468 // Invalidate *source, don't unmap it though since it is already gone.
Alex Lightca97ada2018-02-02 09:25:31 -0800469 size_t source_size = source->size_;
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100470 source->Invalidate();
Alex Lightca97ada2018-02-02 09:25:31 -0800471
472 size_ = source_size;
473 base_size_ = new_base_size;
474 // Reduce base_size if needed (this will unmap the extra pages).
475 SetSize(source_size);
476
477 return true;
478#endif // !HAVE_MREMAP_SYSCALL
479}
480
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100481MemMap MemMap::MapFileAtAddress(uint8_t* expected_ptr,
482 size_t byte_count,
483 int prot,
484 int flags,
485 int fd,
486 off_t start,
487 bool low_4gb,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100488 const char* filename,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100489 bool reuse,
490 /*inout*/MemMap* reservation,
491 /*out*/std::string* error_msg) {
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700492 CHECK_NE(0, prot);
493 CHECK_NE(0, flags & (MAP_SHARED | MAP_PRIVATE));
Narayan Kamathb89c3da2014-08-21 17:38:09 +0100494
Vladimir Markoc09cd052018-08-23 16:36:36 +0100495 // Note that we do not allow MAP_FIXED unless reuse == true or we have an existing
496 // reservation, i.e we expect this mapping to be contained within an existing map.
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700497 if (reuse) {
498 // reuse means it is okay that it overlaps an existing page mapping.
499 // Only use this if you actually made the page reservation yourself.
Jim_Guoa62a5882014-04-28 11:11:57 +0800500 CHECK(expected_ptr != nullptr);
Vladimir Markoc09cd052018-08-23 16:36:36 +0100501 DCHECK(reservation == nullptr);
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800502 DCHECK(error_msg != nullptr);
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800503 DCHECK(ContainedWithinExistingMap(expected_ptr, byte_count, error_msg))
504 << ((error_msg != nullptr) ? *error_msg : std::string());
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700505 flags |= MAP_FIXED;
Vladimir Markoc09cd052018-08-23 16:36:36 +0100506 } else if (reservation != nullptr) {
507 DCHECK(error_msg != nullptr);
508 if (!CheckReservation(expected_ptr, byte_count, filename, *reservation, error_msg)) {
509 return Invalid();
510 }
511 flags |= MAP_FIXED;
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700512 } else {
513 CHECK_EQ(0, flags & MAP_FIXED);
Narayan Kamathb89c3da2014-08-21 17:38:09 +0100514 // Don't bother checking for an overlapping region here. We'll
515 // check this if required after the fact inside CheckMapRequest.
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700516 }
517
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700518 if (byte_count == 0) {
Nicolas Geoffrayc36a8cc2019-04-29 13:37:42 +0100519 *error_msg = "Empty MemMap requested";
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100520 return Invalid();
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700521 }
Ian Rogersf8adc602013-04-18 17:06:19 -0700522 // Adjust 'offset' to be page-aligned as required by mmap.
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700523 int page_offset = start % kPageSize;
524 off_t page_aligned_offset = start - page_offset;
Ian Rogersf8adc602013-04-18 17:06:19 -0700525 // Adjust 'byte_count' to be page-aligned as we will map this anyway.
Elliott Hughesecd3a6f2012-06-06 18:16:37 -0700526 size_t page_aligned_byte_count = RoundUp(byte_count + page_offset, kPageSize);
Jim_Guoa62a5882014-04-28 11:11:57 +0800527 // The 'expected_ptr' is modified (if specified, ie non-null) to be page aligned to the file but
528 // not necessarily to virtual memory. mmap will page align 'expected' for us.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700529 uint8_t* page_aligned_expected =
530 (expected_ptr == nullptr) ? nullptr : (expected_ptr - page_offset);
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700531
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700532 size_t redzone_size = 0;
Roland Levillain05e34f42018-05-24 13:19:05 +0000533 if (kRunningOnMemoryTool && kMemoryToolAddsRedzones && expected_ptr == nullptr) {
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700534 redzone_size = kPageSize;
535 page_aligned_byte_count += redzone_size;
536 }
537
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800538 uint8_t* actual = reinterpret_cast<uint8_t*>(MapInternal(page_aligned_expected,
539 page_aligned_byte_count,
540 prot,
541 flags,
542 fd,
543 page_aligned_offset,
544 low_4gb));
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700545 if (actual == MAP_FAILED) {
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800546 if (error_msg != nullptr) {
547 auto saved_errno = errno;
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700548
Andreas Gampe7ec09042016-04-01 17:20:49 -0700549 if (kIsDebugBuild || VLOG_IS_ON(oat)) {
550 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
551 }
Brian Carlstromaa94cf32014-03-23 23:47:25 -0700552
Mathieu Chartierebe2dfc2015-11-24 13:47:52 -0800553 *error_msg = StringPrintf("mmap(%p, %zd, 0x%x, 0x%x, %d, %" PRId64
554 ") of file '%s' failed: %s. See process maps in the log.",
555 page_aligned_expected, page_aligned_byte_count, prot, flags, fd,
556 static_cast<int64_t>(page_aligned_offset), filename,
557 strerror(saved_errno));
558 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100559 return Invalid();
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700560 }
Jim_Guoa62a5882014-04-28 11:11:57 +0800561 if (!CheckMapRequest(expected_ptr, actual, page_aligned_byte_count, error_msg)) {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100562 return Invalid();
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700563 }
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700564 if (redzone_size != 0) {
565 const uint8_t *real_start = actual + page_offset;
566 const uint8_t *real_end = actual + page_offset + byte_count;
567 const uint8_t *mapping_end = actual + page_aligned_byte_count;
568
569 MEMORY_TOOL_MAKE_NOACCESS(actual, real_start - actual);
570 MEMORY_TOOL_MAKE_NOACCESS(real_end, mapping_end - real_end);
571 page_aligned_byte_count -= redzone_size;
572 }
573
Vladimir Markoc09cd052018-08-23 16:36:36 +0100574 if (reservation != nullptr) {
575 // Re-mapping was successful, transfer the ownership of the memory to the new MemMap.
576 DCHECK_EQ(actual, reservation->Begin());
577 reservation->ReleaseReservedMemory(byte_count);
578 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100579 return MemMap(filename,
580 actual + page_offset,
581 byte_count,
582 actual,
583 page_aligned_byte_count,
584 prot,
585 reuse,
586 redzone_size);
587}
588
Andreas Gampe44b31742018-10-01 19:30:57 -0700589MemMap::MemMap(MemMap&& other) noexcept
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100590 : MemMap() {
591 swap(other);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700592}
593
594MemMap::~MemMap() {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100595 Reset();
596}
597
598void MemMap::DoReset() {
599 DCHECK(IsValid());
Rock.Yeh9a625b52020-01-06 10:53:02 +0800600 size_t real_base_size = base_size_;
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700601 // Unlike Valgrind, AddressSanitizer requires that all manually poisoned memory is unpoisoned
602 // before it is returned to the system.
603 if (redzone_size_ != 0) {
Rock.Yeh9a625b52020-01-06 10:53:02 +0800604 // Add redzone_size_ back to base_size or it will cause a mmap leakage.
605 real_base_size += redzone_size_;
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700606 MEMORY_TOOL_MAKE_UNDEFINED(
Rock.Yeh9a625b52020-01-06 10:53:02 +0800607 reinterpret_cast<char*>(base_begin_) + real_base_size - redzone_size_,
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700608 redzone_size_);
609 }
610
Jim_Guoa62a5882014-04-28 11:11:57 +0800611 if (!reuse_) {
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700612 MEMORY_TOOL_MAKE_UNDEFINED(base_begin_, base_size_);
Alex Lightca97ada2018-02-02 09:25:31 -0800613 if (!already_unmapped_) {
Rock.Yeh9a625b52020-01-06 10:53:02 +0800614 int result = TargetMUnmap(base_begin_, real_base_size);
Alex Lightca97ada2018-02-02 09:25:31 -0800615 if (result == -1) {
616 PLOG(FATAL) << "munmap failed";
617 }
Jim_Guoa62a5882014-04-28 11:11:57 +0800618 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700619 }
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700620
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100621 Invalidate();
622}
623
Nicolas Geoffray88f3fd92019-06-27 16:32:13 +0100624void MemMap::ResetInForkedProcess() {
625 // This should be called on a map that has MADV_DONTFORK.
626 // The kernel has already unmapped this.
627 already_unmapped_ = true;
628 Reset();
629}
630
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100631void MemMap::Invalidate() {
632 DCHECK(IsValid());
633
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700634 // Remove it from gMaps.
David Sehr1b14fb82017-02-01 10:42:11 -0800635 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100636 auto it = GetGMapsEntry(*this);
637 gMaps->erase(it);
638
639 // Mark it as invalid.
640 base_size_ = 0u;
641 DCHECK(!IsValid());
642}
643
644void MemMap::swap(MemMap& other) {
645 if (IsValid() || other.IsValid()) {
646 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
647 DCHECK(gMaps != nullptr);
648 auto this_it = IsValid() ? GetGMapsEntry(*this) : gMaps->end();
649 auto other_it = other.IsValid() ? GetGMapsEntry(other) : gMaps->end();
650 if (IsValid()) {
651 DCHECK(this_it != gMaps->end());
652 DCHECK_EQ(this_it->second, this);
653 this_it->second = &other;
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700654 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100655 if (other.IsValid()) {
656 DCHECK(other_it != gMaps->end());
657 DCHECK_EQ(other_it->second, &other);
658 other_it->second = this;
659 }
660 // Swap members with the `mem_maps_lock_` held so that `base_begin_` matches
661 // with the `gMaps` key when other threads try to use `gMaps`.
662 SwapMembers(other);
663 } else {
664 SwapMembers(other);
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700665 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100666}
667
668void MemMap::SwapMembers(MemMap& other) {
669 name_.swap(other.name_);
670 std::swap(begin_, other.begin_);
671 std::swap(size_, other.size_);
672 std::swap(base_begin_, other.base_begin_);
673 std::swap(base_size_, other.base_size_);
674 std::swap(prot_, other.prot_);
675 std::swap(reuse_, other.reuse_);
676 std::swap(already_unmapped_, other.already_unmapped_);
677 std::swap(redzone_size_, other.redzone_size_);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700678}
679
Ian Rogers13735952014-10-08 12:43:28 -0700680MemMap::MemMap(const std::string& name, uint8_t* begin, size_t size, void* base_begin,
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700681 size_t base_size, int prot, bool reuse, size_t redzone_size)
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700682 : name_(name), begin_(begin), size_(size), base_begin_(base_begin), base_size_(base_size),
Alex Lightca97ada2018-02-02 09:25:31 -0800683 prot_(prot), reuse_(reuse), already_unmapped_(false), redzone_size_(redzone_size) {
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700684 if (size_ == 0) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700685 CHECK(begin_ == nullptr);
686 CHECK(base_begin_ == nullptr);
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700687 CHECK_EQ(base_size_, 0U);
688 } else {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700689 CHECK(begin_ != nullptr);
690 CHECK(base_begin_ != nullptr);
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700691 CHECK_NE(base_size_, 0U);
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700692
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700693 // Add it to gMaps.
David Sehr1b14fb82017-02-01 10:42:11 -0800694 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700695 DCHECK(gMaps != nullptr);
696 gMaps->insert(std::make_pair(base_begin_, this));
Brian Carlstrom9004cb62013-07-26 15:48:31 -0700697 }
Andreas Gampec8ccf682014-09-29 20:07:43 -0700698}
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700699
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100700MemMap MemMap::RemapAtEnd(uint8_t* new_end,
701 const char* tail_name,
702 int tail_prot,
703 std::string* error_msg,
Joel Fernandes (Google)92597a82018-08-17 16:19:19 -0700704 bool use_debug_name) {
Orion Hodson1d3fd082018-09-28 09:38:35 +0100705 return RemapAtEnd(new_end,
706 tail_name,
707 tail_prot,
708 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
Andreas Gampe0de385f2018-10-11 11:11:13 -0700709 /* fd= */ -1,
710 /* offset= */ 0,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100711 error_msg,
712 use_debug_name);
713}
714
715MemMap MemMap::RemapAtEnd(uint8_t* new_end,
716 const char* tail_name,
717 int tail_prot,
718 int flags,
719 int fd,
720 off_t offset,
721 std::string* error_msg,
722 bool use_debug_name) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700723 DCHECK_GE(new_end, Begin());
724 DCHECK_LE(new_end, End());
Ian Rogers13735952014-10-08 12:43:28 -0700725 DCHECK_LE(begin_ + size_, reinterpret_cast<uint8_t*>(base_begin_) + base_size_);
Roland Levillain14d90572015-07-16 10:52:26 +0100726 DCHECK_ALIGNED(begin_, kPageSize);
727 DCHECK_ALIGNED(base_begin_, kPageSize);
728 DCHECK_ALIGNED(reinterpret_cast<uint8_t*>(base_begin_) + base_size_, kPageSize);
729 DCHECK_ALIGNED(new_end, kPageSize);
Ian Rogers13735952014-10-08 12:43:28 -0700730 uint8_t* old_end = begin_ + size_;
731 uint8_t* old_base_end = reinterpret_cast<uint8_t*>(base_begin_) + base_size_;
732 uint8_t* new_base_end = new_end;
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700733 DCHECK_LE(new_base_end, old_base_end);
734 if (new_base_end == old_base_end) {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100735 return Invalid();
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700736 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100737 size_t new_size = new_end - reinterpret_cast<uint8_t*>(begin_);
738 size_t new_base_size = new_base_end - reinterpret_cast<uint8_t*>(base_begin_);
739 DCHECK_LE(begin_ + new_size, reinterpret_cast<uint8_t*>(base_begin_) + new_base_size);
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700740 size_t tail_size = old_end - new_end;
Ian Rogers13735952014-10-08 12:43:28 -0700741 uint8_t* tail_base_begin = new_base_end;
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700742 size_t tail_base_size = old_base_end - new_base_end;
743 DCHECK_EQ(tail_base_begin + tail_base_size, old_base_end);
Roland Levillain14d90572015-07-16 10:52:26 +0100744 DCHECK_ALIGNED(tail_base_size, kPageSize);
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700745
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700746 MEMORY_TOOL_MAKE_UNDEFINED(tail_base_begin, tail_base_size);
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100747 // Note: Do not explicitly unmap the tail region, mmap() with MAP_FIXED automatically
748 // removes old mappings for the overlapping region. This makes the operation atomic
749 // and prevents other threads from racing to allocate memory in the requested region.
Steve Austin882ed6b2018-06-08 11:40:38 -0700750 uint8_t* actual = reinterpret_cast<uint8_t*>(TargetMMap(tail_base_begin,
751 tail_base_size,
752 tail_prot,
753 flags,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100754 fd,
755 offset));
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700756 if (actual == MAP_FAILED) {
Nicolas Geoffray1dd670c2019-06-18 13:45:31 +0100757 *error_msg = StringPrintf("map(%p, %zd, 0x%x, 0x%x, %d, 0) failed: %s. See process "
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800758 "maps in the log.", tail_base_begin, tail_base_size, tail_prot, flags,
Nicolas Geoffray1dd670c2019-06-18 13:45:31 +0100759 fd, strerror(errno));
760 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100761 return Invalid();
Hiroshi Yamauchifd7e7f12013-10-22 14:17:48 -0700762 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100763 // Update *this.
764 if (new_base_size == 0u) {
765 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
766 auto it = GetGMapsEntry(*this);
767 gMaps->erase(it);
768 }
Joel Fernandes (Google)92597a82018-08-17 16:19:19 -0700769
770 if (use_debug_name) {
771 SetDebugName(actual, tail_name, tail_base_size);
772 }
773
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100774 size_ = new_size;
775 base_size_ = new_base_size;
776 // Return the new mapping.
777 return MemMap(tail_name, actual, tail_size, actual, tail_base_size, tail_prot, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700778}
Logan Chiend88fa262012-06-06 15:23:32 +0800779
Vladimir Markoc09cd052018-08-23 16:36:36 +0100780MemMap MemMap::TakeReservedMemory(size_t byte_count) {
781 uint8_t* begin = Begin();
782 ReleaseReservedMemory(byte_count); // Performs necessary DCHECK()s on this reservation.
783 size_t base_size = RoundUp(byte_count, kPageSize);
Andreas Gampe0de385f2018-10-11 11:11:13 -0700784 return MemMap(name_, begin, byte_count, begin, base_size, prot_, /* reuse= */ false);
Vladimir Markoc09cd052018-08-23 16:36:36 +0100785}
786
787void MemMap::ReleaseReservedMemory(size_t byte_count) {
788 // Check the reservation mapping.
789 DCHECK(IsValid());
790 DCHECK(!reuse_);
791 DCHECK(!already_unmapped_);
792 DCHECK_EQ(redzone_size_, 0u);
793 DCHECK_EQ(begin_, base_begin_);
794 DCHECK_EQ(size_, base_size_);
795 DCHECK_ALIGNED(begin_, kPageSize);
796 DCHECK_ALIGNED(size_, kPageSize);
797
798 // Check and round up the `byte_count`.
799 DCHECK_NE(byte_count, 0u);
800 DCHECK_LE(byte_count, size_);
801 byte_count = RoundUp(byte_count, kPageSize);
802
803 if (byte_count == size_) {
804 Invalidate();
805 } else {
806 // Shrink the reservation MemMap and update its `gMaps` entry.
807 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
808 auto it = GetGMapsEntry(*this);
Vladimir Marko22e22232019-02-05 16:35:01 +0000809 auto node = gMaps->extract(it);
Vladimir Markoc09cd052018-08-23 16:36:36 +0100810 begin_ += byte_count;
811 size_ -= byte_count;
812 base_begin_ = begin_;
813 base_size_ = size_;
Vladimir Marko22e22232019-02-05 16:35:01 +0000814 node.key() = base_begin_;
815 gMaps->insert(std::move(node));
Vladimir Markoc09cd052018-08-23 16:36:36 +0100816 }
817}
818
Ian Rogersc5f17732014-06-05 20:48:42 -0700819void MemMap::MadviseDontNeedAndZero() {
820 if (base_begin_ != nullptr || base_size_ != 0) {
821 if (!kMadviseZeroes) {
822 memset(base_begin_, 0, base_size_);
823 }
David Sehr10db8fe2018-07-18 11:01:20 -0700824#ifdef _WIN32
825 // It is benign not to madvise away the pages here.
826 PLOG(WARNING) << "MemMap::MadviseDontNeedAndZero does not madvise on Windows.";
827#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700828 int result = madvise(base_begin_, base_size_, MADV_DONTNEED);
829 if (result == -1) {
830 PLOG(WARNING) << "madvise failed";
831 }
David Sehr10db8fe2018-07-18 11:01:20 -0700832#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700833 }
834}
835
Nicolas Geoffray88f3fd92019-06-27 16:32:13 +0100836int MemMap::MadviseDontFork() {
837#if defined(__linux__)
838 if (base_begin_ != nullptr || base_size_ != 0) {
839 return madvise(base_begin_, base_size_, MADV_DONTFORK);
840 }
841#endif
842 return -1;
843}
844
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000845bool MemMap::Sync() {
David Sehr10db8fe2018-07-18 11:01:20 -0700846#ifdef _WIN32
847 // TODO: add FlushViewOfFile support.
848 PLOG(ERROR) << "MemMap::Sync unsupported on Windows.";
849 return false;
850#else
Roland Levillain0b0d3b42018-06-14 13:55:49 +0100851 // Historical note: To avoid Valgrind errors, we temporarily lifted the lower-end noaccess
852 // protection before passing it to msync() when `redzone_size_` was non-null, as Valgrind
853 // only accepts page-aligned base address, and excludes the higher-end noaccess protection
854 // from the msync range. b/27552451.
855 return msync(BaseBegin(), BaseSize(), MS_SYNC) == 0;
David Sehr10db8fe2018-07-18 11:01:20 -0700856#endif
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000857}
858
Logan Chiend88fa262012-06-06 15:23:32 +0800859bool MemMap::Protect(int prot) {
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700860 if (base_begin_ == nullptr && base_size_ == 0) {
Ian Rogers1c849e52012-06-28 14:00:33 -0700861 prot_ = prot;
Logan Chiend88fa262012-06-06 15:23:32 +0800862 return true;
863 }
864
David Sehr10db8fe2018-07-18 11:01:20 -0700865#ifndef _WIN32
Logan Chiend88fa262012-06-06 15:23:32 +0800866 if (mprotect(base_begin_, base_size_, prot) == 0) {
Ian Rogers1c849e52012-06-28 14:00:33 -0700867 prot_ = prot;
Logan Chiend88fa262012-06-06 15:23:32 +0800868 return true;
869 }
David Sehr10db8fe2018-07-18 11:01:20 -0700870#endif
Logan Chiend88fa262012-06-06 15:23:32 +0800871
Shih-wei Liaoa060ed92012-06-07 09:25:28 -0700872 PLOG(ERROR) << "mprotect(" << reinterpret_cast<void*>(base_begin_) << ", " << base_size_ << ", "
873 << prot << ") failed";
Logan Chiend88fa262012-06-06 15:23:32 +0800874 return false;
875}
876
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100877bool MemMap::CheckNoGaps(MemMap& begin_map, MemMap& end_map) {
David Sehr1b14fb82017-02-01 10:42:11 -0800878 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100879 CHECK(begin_map.IsValid());
880 CHECK(end_map.IsValid());
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700881 CHECK(HasMemMap(begin_map));
882 CHECK(HasMemMap(end_map));
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100883 CHECK_LE(begin_map.BaseBegin(), end_map.BaseBegin());
884 MemMap* map = &begin_map;
885 while (map->BaseBegin() != end_map.BaseBegin()) {
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700886 MemMap* next_map = GetLargestMemMapAt(map->BaseEnd());
887 if (next_map == nullptr) {
888 // Found a gap.
889 return false;
890 }
891 map = next_map;
892 }
893 return true;
894}
895
Vladimir Marko17a924a2015-05-08 15:17:32 +0100896void MemMap::DumpMaps(std::ostream& os, bool terse) {
David Sehr1b14fb82017-02-01 10:42:11 -0800897 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Vladimir Marko17a924a2015-05-08 15:17:32 +0100898 DumpMapsLocked(os, terse);
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700899}
900
Vladimir Marko17a924a2015-05-08 15:17:32 +0100901void MemMap::DumpMapsLocked(std::ostream& os, bool terse) {
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700902 const auto& mem_maps = *gMaps;
Vladimir Marko17a924a2015-05-08 15:17:32 +0100903 if (!terse) {
904 os << mem_maps;
905 return;
906 }
907
908 // Terse output example:
909 // [MemMap: 0x409be000+0x20P~0x11dP+0x20P~0x61cP+0x20P prot=0x3 LinearAlloc]
910 // [MemMap: 0x451d6000+0x6bP(3) prot=0x3 large object space allocation]
911 // The details:
912 // "+0x20P" means 0x20 pages taken by a single mapping,
913 // "~0x11dP" means a gap of 0x11d pages,
914 // "+0x6bP(3)" means 3 mappings one after another, together taking 0x6b pages.
915 os << "MemMap:" << std::endl;
916 for (auto it = mem_maps.begin(), maps_end = mem_maps.end(); it != maps_end;) {
917 MemMap* map = it->second;
918 void* base = it->first;
919 CHECK_EQ(base, map->BaseBegin());
920 os << "[MemMap: " << base;
921 ++it;
922 // Merge consecutive maps with the same protect flags and name.
923 constexpr size_t kMaxGaps = 9;
924 size_t num_gaps = 0;
925 size_t num = 1u;
926 size_t size = map->BaseSize();
Roland Levillain14d90572015-07-16 10:52:26 +0100927 CHECK_ALIGNED(size, kPageSize);
Vladimir Marko17a924a2015-05-08 15:17:32 +0100928 void* end = map->BaseEnd();
929 while (it != maps_end &&
930 it->second->GetProtect() == map->GetProtect() &&
931 it->second->GetName() == map->GetName() &&
932 (it->second->BaseBegin() == end || num_gaps < kMaxGaps)) {
933 if (it->second->BaseBegin() != end) {
934 ++num_gaps;
935 os << "+0x" << std::hex << (size / kPageSize) << "P";
936 if (num != 1u) {
937 os << "(" << std::dec << num << ")";
938 }
939 size_t gap =
940 reinterpret_cast<uintptr_t>(it->second->BaseBegin()) - reinterpret_cast<uintptr_t>(end);
Roland Levillain14d90572015-07-16 10:52:26 +0100941 CHECK_ALIGNED(gap, kPageSize);
Vladimir Marko17a924a2015-05-08 15:17:32 +0100942 os << "~0x" << std::hex << (gap / kPageSize) << "P";
943 num = 0u;
944 size = 0u;
945 }
Roland Levillain14d90572015-07-16 10:52:26 +0100946 CHECK_ALIGNED(it->second->BaseSize(), kPageSize);
Vladimir Marko17a924a2015-05-08 15:17:32 +0100947 ++num;
948 size += it->second->BaseSize();
949 end = it->second->BaseEnd();
950 ++it;
951 }
952 os << "+0x" << std::hex << (size / kPageSize) << "P";
953 if (num != 1u) {
954 os << "(" << std::dec << num << ")";
955 }
956 os << " prot=0x" << std::hex << map->GetProtect() << " " << map->GetName() << "]" << std::endl;
957 }
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700958}
959
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100960bool MemMap::HasMemMap(MemMap& map) {
961 void* base_begin = map.BaseBegin();
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700962 for (auto it = gMaps->lower_bound(base_begin), end = gMaps->end();
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700963 it != end && it->first == base_begin; ++it) {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100964 if (it->second == &map) {
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700965 return true;
966 }
967 }
968 return false;
969}
970
971MemMap* MemMap::GetLargestMemMapAt(void* address) {
972 size_t largest_size = 0;
973 MemMap* largest_map = nullptr;
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700974 DCHECK(gMaps != nullptr);
975 for (auto it = gMaps->lower_bound(address), end = gMaps->end();
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700976 it != end && it->first == address; ++it) {
977 MemMap* map = it->second;
978 CHECK(map != nullptr);
979 if (largest_size < map->BaseSize()) {
980 largest_size = map->BaseSize();
981 largest_map = map;
982 }
983 }
984 return largest_map;
985}
986
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700987void MemMap::Init() {
David Sehr1b14fb82017-02-01 10:42:11 -0800988 if (mem_maps_lock_ != nullptr) {
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700989 // dex2oat calls MemMap::Init twice since its needed before the runtime is created.
David Sehr1b14fb82017-02-01 10:42:11 -0800990 return;
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700991 }
David Sehr1b14fb82017-02-01 10:42:11 -0800992 mem_maps_lock_ = new std::mutex();
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700993 // Not for thread safety, but for the annotation that gMaps is GUARDED_BY(mem_maps_lock_).
David Sehr1b14fb82017-02-01 10:42:11 -0800994 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Andreas Gampe0dfc3152017-04-24 07:58:06 -0700995 DCHECK(gMaps == nullptr);
996 gMaps = new Maps;
Steve Austin882ed6b2018-06-08 11:40:38 -0700997
998 TargetMMapInit();
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700999}
1000
1001void MemMap::Shutdown() {
David Sehr1b14fb82017-02-01 10:42:11 -08001002 if (mem_maps_lock_ == nullptr) {
1003 // If MemMap::Shutdown is called more than once, there is no effect.
1004 return;
1005 }
1006 {
Andreas Gampe0dfc3152017-04-24 07:58:06 -07001007 // Not for thread safety, but for the annotation that gMaps is GUARDED_BY(mem_maps_lock_).
David Sehr1b14fb82017-02-01 10:42:11 -08001008 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Andreas Gampe0dfc3152017-04-24 07:58:06 -07001009 DCHECK(gMaps != nullptr);
1010 delete gMaps;
1011 gMaps = nullptr;
David Sehr1b14fb82017-02-01 10:42:11 -08001012 }
1013 delete mem_maps_lock_;
1014 mem_maps_lock_ = nullptr;
Mathieu Chartier6e88ef62014-10-14 15:01:24 -07001015}
1016
Mathieu Chartier379d09f2015-01-08 11:28:13 -08001017void MemMap::SetSize(size_t new_size) {
Alex Lightca97ada2018-02-02 09:25:31 -08001018 CHECK_LE(new_size, size_);
1019 size_t new_base_size = RoundUp(new_size + static_cast<size_t>(PointerDiff(Begin(), BaseBegin())),
1020 kPageSize);
1021 if (new_base_size == base_size_) {
1022 size_ = new_size;
Mathieu Chartier379d09f2015-01-08 11:28:13 -08001023 return;
1024 }
Alex Lightca97ada2018-02-02 09:25:31 -08001025 CHECK_LT(new_base_size, base_size_);
Evgenii Stepanov1e133742015-05-20 12:30:59 -07001026 MEMORY_TOOL_MAKE_UNDEFINED(
1027 reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(BaseBegin()) +
Alex Lightca97ada2018-02-02 09:25:31 -08001028 new_base_size),
1029 base_size_ - new_base_size);
Steve Austin882ed6b2018-06-08 11:40:38 -07001030 CHECK_EQ(TargetMUnmap(reinterpret_cast<void*>(
1031 reinterpret_cast<uintptr_t>(BaseBegin()) + new_base_size),
1032 base_size_ - new_base_size), 0)
1033 << new_base_size << " " << base_size_;
Alex Lightca97ada2018-02-02 09:25:31 -08001034 base_size_ = new_base_size;
Mathieu Chartier379d09f2015-01-08 11:28:13 -08001035 size_ = new_size;
1036}
1037
Andreas Gampe651ba592017-06-14 14:41:33 -07001038void* MemMap::MapInternalArtLow4GBAllocator(size_t length,
1039 int prot,
1040 int flags,
1041 int fd,
1042 off_t offset) {
1043#if USE_ART_LOW_4G_ALLOCATOR
1044 void* actual = MAP_FAILED;
1045
1046 bool first_run = true;
1047
1048 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
1049 for (uintptr_t ptr = next_mem_pos_; ptr < 4 * GB; ptr += kPageSize) {
1050 // Use gMaps as an optimization to skip over large maps.
1051 // Find the first map which is address > ptr.
1052 auto it = gMaps->upper_bound(reinterpret_cast<void*>(ptr));
1053 if (it != gMaps->begin()) {
1054 auto before_it = it;
1055 --before_it;
1056 // Start at the end of the map before the upper bound.
1057 ptr = std::max(ptr, reinterpret_cast<uintptr_t>(before_it->second->BaseEnd()));
1058 CHECK_ALIGNED(ptr, kPageSize);
1059 }
1060 while (it != gMaps->end()) {
1061 // How much space do we have until the next map?
1062 size_t delta = reinterpret_cast<uintptr_t>(it->first) - ptr;
1063 // If the space may be sufficient, break out of the loop.
1064 if (delta >= length) {
1065 break;
1066 }
1067 // Otherwise, skip to the end of the map.
1068 ptr = reinterpret_cast<uintptr_t>(it->second->BaseEnd());
1069 CHECK_ALIGNED(ptr, kPageSize);
1070 ++it;
1071 }
1072
1073 // Try to see if we get lucky with this address since none of the ART maps overlap.
1074 actual = TryMemMapLow4GB(reinterpret_cast<void*>(ptr), length, prot, flags, fd, offset);
1075 if (actual != MAP_FAILED) {
1076 next_mem_pos_ = reinterpret_cast<uintptr_t>(actual) + length;
1077 return actual;
1078 }
1079
1080 if (4U * GB - ptr < length) {
1081 // Not enough memory until 4GB.
1082 if (first_run) {
1083 // Try another time from the bottom;
1084 ptr = LOW_MEM_START - kPageSize;
1085 first_run = false;
1086 continue;
1087 } else {
1088 // Second try failed.
1089 break;
1090 }
1091 }
1092
1093 uintptr_t tail_ptr;
1094
1095 // Check pages are free.
1096 bool safe = true;
1097 for (tail_ptr = ptr; tail_ptr < ptr + length; tail_ptr += kPageSize) {
1098 if (msync(reinterpret_cast<void*>(tail_ptr), kPageSize, 0) == 0) {
1099 safe = false;
1100 break;
1101 } else {
1102 DCHECK_EQ(errno, ENOMEM);
1103 }
1104 }
1105
1106 next_mem_pos_ = tail_ptr; // update early, as we break out when we found and mapped a region
1107
1108 if (safe == true) {
1109 actual = TryMemMapLow4GB(reinterpret_cast<void*>(ptr), length, prot, flags, fd, offset);
1110 if (actual != MAP_FAILED) {
1111 return actual;
1112 }
1113 } else {
1114 // Skip over last page.
1115 ptr = tail_ptr;
1116 }
1117 }
1118
1119 if (actual == MAP_FAILED) {
1120 LOG(ERROR) << "Could not find contiguous low-memory space.";
1121 errno = ENOMEM;
1122 }
1123 return actual;
1124#else
1125 UNUSED(length, prot, flags, fd, offset);
1126 LOG(FATAL) << "Unreachable";
1127 UNREACHABLE();
1128#endif
1129}
1130
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001131void* MemMap::MapInternal(void* addr,
1132 size_t length,
1133 int prot,
1134 int flags,
1135 int fd,
1136 off_t offset,
1137 bool low_4gb) {
1138#ifdef __LP64__
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001139 // When requesting low_4g memory and having an expectation, the requested range should fit into
1140 // 4GB.
1141 if (low_4gb && (
1142 // Start out of bounds.
1143 (reinterpret_cast<uintptr_t>(addr) >> 32) != 0 ||
1144 // End out of bounds. For simplicity, this will fail for the last page of memory.
1145 ((reinterpret_cast<uintptr_t>(addr) + length) >> 32) != 0)) {
1146 LOG(ERROR) << "The requested address space (" << addr << ", "
1147 << reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(addr) + length)
1148 << ") cannot fit in low_4gb";
1149 return MAP_FAILED;
1150 }
1151#else
1152 UNUSED(low_4gb);
1153#endif
1154 DCHECK_ALIGNED(length, kPageSize);
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001155 // TODO:
1156 // A page allocator would be a useful abstraction here, as
1157 // 1) It is doubtful that MAP_32BIT on x86_64 is doing the right job for us
1158 void* actual = MAP_FAILED;
1159#if USE_ART_LOW_4G_ALLOCATOR
1160 // MAP_32BIT only available on x86_64.
1161 if (low_4gb && addr == nullptr) {
Andreas Gampe651ba592017-06-14 14:41:33 -07001162 // The linear-scan allocator has an issue when executable pages are denied (e.g., by selinux
1163 // policies in sensitive processes). In that case, the error code will still be ENOMEM. So
1164 // the allocator will scan all low 4GB twice, and still fail. This is *very* slow.
1165 //
1166 // To avoid the issue, always map non-executable first, and mprotect if necessary.
1167 const int orig_prot = prot;
1168 const int prot_non_exec = prot & ~PROT_EXEC;
1169 actual = MapInternalArtLow4GBAllocator(length, prot_non_exec, flags, fd, offset);
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001170
1171 if (actual == MAP_FAILED) {
Andreas Gampe651ba592017-06-14 14:41:33 -07001172 return MAP_FAILED;
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001173 }
Andreas Gampe651ba592017-06-14 14:41:33 -07001174
1175 // See if we need to remap with the executable bit now.
1176 if (orig_prot != prot_non_exec) {
1177 if (mprotect(actual, length, orig_prot) != 0) {
1178 PLOG(ERROR) << "Could not protect to requested prot: " << orig_prot;
Steve Austin882ed6b2018-06-08 11:40:38 -07001179 TargetMUnmap(actual, length);
Andreas Gampe651ba592017-06-14 14:41:33 -07001180 errno = ENOMEM;
1181 return MAP_FAILED;
1182 }
1183 }
1184 return actual;
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001185 }
1186
Steve Austin882ed6b2018-06-08 11:40:38 -07001187 actual = TargetMMap(addr, length, prot, flags, fd, offset);
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001188#else
1189#if defined(__LP64__)
1190 if (low_4gb && addr == nullptr) {
1191 flags |= MAP_32BIT;
1192 }
1193#endif
Steve Austin882ed6b2018-06-08 11:40:38 -07001194 actual = TargetMMap(addr, length, prot, flags, fd, offset);
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001195#endif
1196 return actual;
1197}
1198
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001199std::ostream& operator<<(std::ostream& os, const MemMap& mem_map) {
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -07001200 os << StringPrintf("[MemMap: %p-%p prot=0x%x %s]",
1201 mem_map.BaseBegin(), mem_map.BaseEnd(), mem_map.GetProtect(),
1202 mem_map.GetName().c_str());
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001203 return os;
1204}
1205
Hiroshi Yamauchi6edb9ae2016-02-08 14:18:21 -08001206void MemMap::TryReadable() {
1207 if (base_begin_ == nullptr && base_size_ == 0) {
1208 return;
1209 }
1210 CHECK_NE(prot_ & PROT_READ, 0);
1211 volatile uint8_t* begin = reinterpret_cast<volatile uint8_t*>(base_begin_);
1212 volatile uint8_t* end = begin + base_size_;
1213 DCHECK(IsAligned<kPageSize>(begin));
1214 DCHECK(IsAligned<kPageSize>(end));
1215 // Read the first byte of each page. Use volatile to prevent the compiler from optimizing away the
1216 // reads.
1217 for (volatile uint8_t* ptr = begin; ptr < end; ptr += kPageSize) {
1218 // This read could fault if protection wasn't set correctly.
1219 uint8_t value = *ptr;
1220 UNUSED(value);
1221 }
1222}
1223
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07001224void ZeroAndReleasePages(void* address, size_t length) {
Mathieu Chartier7c928f02017-06-05 17:23:44 -07001225 if (length == 0) {
1226 return;
1227 }
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07001228 uint8_t* const mem_begin = reinterpret_cast<uint8_t*>(address);
1229 uint8_t* const mem_end = mem_begin + length;
1230 uint8_t* const page_begin = AlignUp(mem_begin, kPageSize);
1231 uint8_t* const page_end = AlignDown(mem_end, kPageSize);
1232 if (!kMadviseZeroes || page_begin >= page_end) {
1233 // No possible area to madvise.
1234 std::fill(mem_begin, mem_end, 0);
1235 } else {
1236 // Spans one or more pages.
1237 DCHECK_LE(mem_begin, page_begin);
1238 DCHECK_LE(page_begin, page_end);
1239 DCHECK_LE(page_end, mem_end);
1240 std::fill(mem_begin, page_begin, 0);
David Sehr10db8fe2018-07-18 11:01:20 -07001241#ifdef _WIN32
1242 LOG(WARNING) << "ZeroAndReleasePages does not madvise on Windows.";
1243#else
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07001244 CHECK_NE(madvise(page_begin, page_end - page_begin, MADV_DONTNEED), -1) << "madvise failed";
David Sehr10db8fe2018-07-18 11:01:20 -07001245#endif
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07001246 std::fill(page_end, mem_end, 0);
1247 }
1248}
1249
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -08001250void MemMap::AlignBy(size_t size) {
1251 CHECK_EQ(begin_, base_begin_) << "Unsupported";
1252 CHECK_EQ(size_, base_size_) << "Unsupported";
1253 CHECK_GT(size, static_cast<size_t>(kPageSize));
1254 CHECK_ALIGNED(size, kPageSize);
Vladimir Markoc34bebf2018-08-16 16:12:49 +01001255 CHECK(!reuse_);
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -08001256 if (IsAlignedParam(reinterpret_cast<uintptr_t>(base_begin_), size) &&
1257 IsAlignedParam(base_size_, size)) {
1258 // Already aligned.
1259 return;
1260 }
1261 uint8_t* base_begin = reinterpret_cast<uint8_t*>(base_begin_);
1262 uint8_t* base_end = base_begin + base_size_;
1263 uint8_t* aligned_base_begin = AlignUp(base_begin, size);
1264 uint8_t* aligned_base_end = AlignDown(base_end, size);
1265 CHECK_LE(base_begin, aligned_base_begin);
1266 CHECK_LE(aligned_base_end, base_end);
1267 size_t aligned_base_size = aligned_base_end - aligned_base_begin;
1268 CHECK_LT(aligned_base_begin, aligned_base_end)
1269 << "base_begin = " << reinterpret_cast<void*>(base_begin)
1270 << " base_end = " << reinterpret_cast<void*>(base_end);
1271 CHECK_GE(aligned_base_size, size);
1272 // Unmap the unaligned parts.
1273 if (base_begin < aligned_base_begin) {
1274 MEMORY_TOOL_MAKE_UNDEFINED(base_begin, aligned_base_begin - base_begin);
Steve Austin882ed6b2018-06-08 11:40:38 -07001275 CHECK_EQ(TargetMUnmap(base_begin, aligned_base_begin - base_begin), 0)
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -08001276 << "base_begin=" << reinterpret_cast<void*>(base_begin)
1277 << " aligned_base_begin=" << reinterpret_cast<void*>(aligned_base_begin);
1278 }
1279 if (aligned_base_end < base_end) {
1280 MEMORY_TOOL_MAKE_UNDEFINED(aligned_base_end, base_end - aligned_base_end);
Steve Austin882ed6b2018-06-08 11:40:38 -07001281 CHECK_EQ(TargetMUnmap(aligned_base_end, base_end - aligned_base_end), 0)
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -08001282 << "base_end=" << reinterpret_cast<void*>(base_end)
1283 << " aligned_base_end=" << reinterpret_cast<void*>(aligned_base_end);
1284 }
1285 std::lock_guard<std::mutex> mu(*mem_maps_lock_);
Vladimir Markoc34bebf2018-08-16 16:12:49 +01001286 if (base_begin < aligned_base_begin) {
1287 auto it = GetGMapsEntry(*this);
Vladimir Marko22e22232019-02-05 16:35:01 +00001288 auto node = gMaps->extract(it);
1289 node.key() = aligned_base_begin;
1290 gMaps->insert(std::move(node));
Vladimir Markoc34bebf2018-08-16 16:12:49 +01001291 }
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -08001292 base_begin_ = aligned_base_begin;
1293 base_size_ = aligned_base_size;
1294 begin_ = aligned_base_begin;
1295 size_ = aligned_base_size;
Andreas Gampe0dfc3152017-04-24 07:58:06 -07001296 DCHECK(gMaps != nullptr);
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -08001297}
1298
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001299} // namespace art