1 /*
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 
19 #include <inttypes.h>
20 #include <stdlib.h>
21 #if !defined(ANDROID_OS) && !defined(__Fuchsia__) && !defined(_WIN32)
22 #include <sys/resource.h>
23 #endif
24 
25 #if defined(__linux__)
26 #include <sys/prctl.h>
27 #endif
28 
29 #include <map>
30 #include <memory>
31 #include <sstream>
32 
33 #include "android-base/stringprintf.h"
34 #include "android-base/unique_fd.h"
35 
36 #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"
41 #include "mman.h"  // For the PROT_* and MAP_* constants.
42 #include "utils.h"
43 
44 #ifndef MAP_ANONYMOUS
45 #define MAP_ANONYMOUS MAP_ANON
46 #endif
47 
48 namespace art {
49 
50 using android::base::StringPrintf;
51 using android::base::unique_fd;
52 
53 template<class Key, class T, AllocatorTag kTag, class Compare = std::less<Key>>
54 using AllocationTrackingMultiMap =
55     std::multimap<Key, T, Compare, TrackingAllocator<std::pair<const Key, T>, kTag>>;
56 
57 using 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()).
60 static Maps* gMaps GUARDED_BY(MemMap::GetMemMapsLock()) = nullptr;
61 
62 // A map containing unique strings used for indentifying anonymous mappings
63 static std::map<std::string, int> debugStrMap GUARDED_BY(MemMap::GetMemMapsLock());
64 
65 // Retrieve iterator to a `gMaps` entry that is known to exist.
GetGMapsEntry(const MemMap & map)66 Maps::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 
operator <<(std::ostream & os,const Maps & mem_maps)80 std::ostream& operator<<(std::ostream& os, const Maps& mem_maps) {
81   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 
91 std::mutex* MemMap::mem_maps_lock_ = nullptr;
92 
93 #if USE_ART_LOW_4G_ALLOCATOR
94 // 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.
97 static constexpr uintptr_t LOW_MEM_START = 64 * KB;
98 
99 // 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 //
116 // arc4random as an entropy source is exposed in Bionic, but not in glibc. When we
117 // 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__
CreateStartPos(uint64_t input)121 uintptr_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 
GenerateNextMemPos()136 static uintptr_t GenerateNextMemPos() {
137 #ifdef __BIONIC__
138   uint64_t random_data;
139   arc4random_buf(&random_data, sizeof(random_data));
140   return CreateStartPos(random_data);
141 #else
142   // No arc4random on host, see above.
143   return LOW_MEM_START;
144 #endif
145 }
146 
147 // Initialize linear scan to random position.
148 uintptr_t MemMap::next_mem_pos_ = GenerateNextMemPos();
149 #endif
150 
151 // Return true if the address range is contained in a single memory map by either reading
152 // the gMaps variable or the /proc/self/map entry.
ContainedWithinExistingMap(uint8_t * ptr,size_t size,std::string * error_msg)153 bool MemMap::ContainedWithinExistingMap(uint8_t* ptr, size_t size, std::string* error_msg) {
154   uintptr_t begin = reinterpret_cast<uintptr_t>(ptr);
155   uintptr_t end = begin + size;
156 
157   {
158     std::lock_guard<std::mutex> mu(*mem_maps_lock_);
159     for (auto& pair : *gMaps) {
160       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 
168   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   }
173   return false;
174 }
175 
176 // 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 //
180 // If the expected_ptr is null, nothing is checked beyond the fact
181 // 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.
CheckMapRequest(uint8_t * expected_ptr,void * actual_ptr,size_t byte_count,std::string * error_msg)185 bool MemMap::CheckMapRequest(uint8_t* expected_ptr, void* actual_ptr, size_t byte_count,
186                             std::string* error_msg) {
187   // Handled first by caller for more specific error messages.
188   CHECK(actual_ptr != MAP_FAILED);
189 
190   if (expected_ptr == nullptr) {
191     return true;
192   }
193 
194   uintptr_t actual = reinterpret_cast<uintptr_t>(actual_ptr);
195   uintptr_t expected = reinterpret_cast<uintptr_t>(expected_ptr);
196 
197   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.
202   int result = TargetMUnmap(actual_ptr, byte_count);
203   if (result == -1) {
204     PLOG(WARNING) << StringPrintf("munmap(%p, %zd) failed", actual_ptr, byte_count);
205   }
206 
207   if (error_msg != nullptr) {
208     // 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.
215 
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 
221     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);
225     *error_msg = os.str();
226   }
227   return false;
228 }
229 
CheckReservation(uint8_t * expected_ptr,size_t byte_count,const char * name,const MemMap & reservation,std::string * error_msg)230 bool 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 
257 #if USE_ART_LOW_4G_ALLOCATOR
TryMemMapLow4GB(void * ptr,size_t page_aligned_byte_count,int prot,int flags,int fd,off_t offset)258 void* MemMap::TryMemMapLow4GB(void* ptr,
259                                     size_t page_aligned_byte_count,
260                                     int prot,
261                                     int flags,
262                                     int fd,
263                                     off_t offset) {
264   void* actual = TargetMMap(ptr, page_aligned_byte_count, prot, flags, fd, offset);
265   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) {
269       TargetMUnmap(actual, page_aligned_byte_count);
270       actual = MAP_FAILED;
271     }
272   }
273   return actual;
274 }
275 #endif
276 
SetDebugName(void * map_ptr,const char * name,size_t size)277 void 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 
MapAnonymous(const char * name,uint8_t * addr,size_t byte_count,int prot,bool low_4gb,bool reuse,MemMap * reservation,std::string * error_msg,bool use_debug_name)304 MemMap MemMap::MapAnonymous(const char* name,
305                             uint8_t* addr,
306                             size_t byte_count,
307                             int prot,
308                             bool low_4gb,
309                             bool reuse,
310                             /*inout*/MemMap* reservation,
311                             /*out*/std::string* error_msg,
312                             bool use_debug_name) {
313 #ifndef __LP64__
314   UNUSED(low_4gb);
315 #endif
316   if (byte_count == 0) {
317     *error_msg = "Empty MemMap requested.";
318     return Invalid();
319   }
320   size_t page_aligned_byte_count = RoundUp(byte_count, kPageSize);
321 
322   int flags = MAP_PRIVATE | MAP_ANONYMOUS;
323   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.
326     CHECK(addr != nullptr);
327     DCHECK(reservation == nullptr);
328 
329     DCHECK(ContainedWithinExistingMap(addr, byte_count, error_msg)) << *error_msg;
330     flags |= MAP_FIXED;
331   } 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;
337   }
338 
339   unique_fd fd;
340 
341   // We need to store and potentially set an error number for pretty printing of errors
342   int saved_errno = 0;
343 
344   void* actual = MapInternal(addr,
345                              page_aligned_byte_count,
346                              prot,
347                              flags,
348                              fd.get(),
349                              0,
350                              low_4gb);
351   saved_errno = errno;
352 
353   if (actual == MAP_FAILED) {
354     if (error_msg != nullptr) {
355       if (kIsDebugBuild || VLOG_IS_ON(oat)) {
356         PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
357       }
358 
359       *error_msg = StringPrintf("Failed anonymous mmap(%p, %zd, 0x%x, 0x%x, %d, 0): %s. "
360                                     "See process maps in the log.",
361                                 addr,
362                                 page_aligned_byte_count,
363                                 prot,
364                                 flags,
365                                 fd.get(),
366                                 strerror(saved_errno));
367     }
368     return Invalid();
369   }
370   if (!CheckMapRequest(addr, actual, page_aligned_byte_count, error_msg)) {
371     return Invalid();
372   }
373 
374   if (use_debug_name) {
375     SetDebugName(actual, name, page_aligned_byte_count);
376   }
377 
378   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   }
383   return MemMap(name,
384                 reinterpret_cast<uint8_t*>(actual),
385                 byte_count,
386                 actual,
387                 page_aligned_byte_count,
388                 prot,
389                 reuse);
390 }
391 
MapPlaceholder(const char * name,uint8_t * addr,size_t byte_count)392 MemMap MemMap::MapPlaceholder(const char* name, uint8_t* addr, size_t byte_count) {
393   if (byte_count == 0) {
394     return Invalid();
395   }
396   const size_t page_aligned_byte_count = RoundUp(byte_count, kPageSize);
397   return MemMap(name, addr, byte_count, addr, page_aligned_byte_count, 0, /* reuse= */ true);
398 }
399 
400 template<typename A, typename B>
PointerDiff(A * a,B * b)401 static 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 
ReplaceWith(MemMap * source,std::string * error)405 bool MemMap::ReplaceWith(MemMap* source, /*out*/std::string* error) {
406 #if !HAVE_MREMAP_SYSCALL
407   UNUSED(source);
408   *error = "Cannot perform atomic replace because we are missing the required mremap syscall";
409   return false;
410 #else  // !HAVE_MREMAP_SYSCALL
411   CHECK(source != nullptr);
412   CHECK(source->IsValid());
413   if (!MemMap::kCanReplaceMapping) {
414     *error = "Unable to perform atomic replace due to runtime environment!";
415     return false;
416   }
417   // 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 
468   // Invalidate *source, don't unmap it though since it is already gone.
469   size_t source_size = source->size_;
470   source->Invalidate();
471 
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 
MapFileAtAddress(uint8_t * expected_ptr,size_t byte_count,int prot,int flags,int fd,off_t start,bool low_4gb,const char * filename,bool reuse,MemMap * reservation,std::string * error_msg)481 MemMap 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,
488                                 const char* filename,
489                                 bool reuse,
490                                 /*inout*/MemMap* reservation,
491                                 /*out*/std::string* error_msg) {
492   CHECK_NE(0, prot);
493   CHECK_NE(0, flags & (MAP_SHARED | MAP_PRIVATE));
494 
495   // 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.
497   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.
500     CHECK(expected_ptr != nullptr);
501     DCHECK(reservation == nullptr);
502     DCHECK(error_msg != nullptr);
503     DCHECK(ContainedWithinExistingMap(expected_ptr, byte_count, error_msg))
504         << ((error_msg != nullptr) ? *error_msg : std::string());
505     flags |= MAP_FIXED;
506   } 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;
512   } else {
513     CHECK_EQ(0, flags & MAP_FIXED);
514     // Don't bother checking for an overlapping region here. We'll
515     // check this if required after the fact inside CheckMapRequest.
516   }
517 
518   if (byte_count == 0) {
519     *error_msg = "Empty MemMap requested";
520     return Invalid();
521   }
522   // Adjust 'offset' to be page-aligned as required by mmap.
523   int page_offset = start % kPageSize;
524   off_t page_aligned_offset = start - page_offset;
525   // Adjust 'byte_count' to be page-aligned as we will map this anyway.
526   size_t page_aligned_byte_count = RoundUp(byte_count + page_offset, kPageSize);
527   // 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.
529   uint8_t* page_aligned_expected =
530       (expected_ptr == nullptr) ? nullptr : (expected_ptr - page_offset);
531 
532   size_t redzone_size = 0;
533   if (kRunningOnMemoryTool && kMemoryToolAddsRedzones && expected_ptr == nullptr) {
534     redzone_size = kPageSize;
535     page_aligned_byte_count += redzone_size;
536   }
537 
538   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));
545   if (actual == MAP_FAILED) {
546     if (error_msg != nullptr) {
547       auto saved_errno = errno;
548 
549       if (kIsDebugBuild || VLOG_IS_ON(oat)) {
550         PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
551       }
552 
553       *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     }
559     return Invalid();
560   }
561   if (!CheckMapRequest(expected_ptr, actual, page_aligned_byte_count, error_msg)) {
562     return Invalid();
563   }
564   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 
574   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   }
579   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 
MemMap(MemMap && other)589 MemMap::MemMap(MemMap&& other) noexcept
590     : MemMap() {
591   swap(other);
592 }
593 
~MemMap()594 MemMap::~MemMap() {
595   Reset();
596 }
597 
DoReset()598 void MemMap::DoReset() {
599   DCHECK(IsValid());
600   size_t real_base_size = base_size_;
601   // Unlike Valgrind, AddressSanitizer requires that all manually poisoned memory is unpoisoned
602   // before it is returned to the system.
603   if (redzone_size_ != 0) {
604     // Add redzone_size_ back to base_size or it will cause a mmap leakage.
605     real_base_size += redzone_size_;
606     MEMORY_TOOL_MAKE_UNDEFINED(
607         reinterpret_cast<char*>(base_begin_) + real_base_size - redzone_size_,
608         redzone_size_);
609   }
610 
611   if (!reuse_) {
612     MEMORY_TOOL_MAKE_UNDEFINED(base_begin_, base_size_);
613     if (!already_unmapped_) {
614       int result = TargetMUnmap(base_begin_, real_base_size);
615       if (result == -1) {
616         PLOG(FATAL) << "munmap failed";
617       }
618     }
619   }
620 
621   Invalidate();
622 }
623 
ResetInForkedProcess()624 void 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 
Invalidate()631 void MemMap::Invalidate() {
632   DCHECK(IsValid());
633 
634   // Remove it from gMaps.
635   std::lock_guard<std::mutex> mu(*mem_maps_lock_);
636   auto it = GetGMapsEntry(*this);
637   gMaps->erase(it);
638 
639   // Mark it as invalid.
640   base_size_ = 0u;
641   DCHECK(!IsValid());
642 }
643 
swap(MemMap & other)644 void 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;
654     }
655     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);
665   }
666 }
667 
SwapMembers(MemMap & other)668 void 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_);
678 }
679 
MemMap(const std::string & name,uint8_t * begin,size_t size,void * base_begin,size_t base_size,int prot,bool reuse,size_t redzone_size)680 MemMap::MemMap(const std::string& name, uint8_t* begin, size_t size, void* base_begin,
681                size_t base_size, int prot, bool reuse, size_t redzone_size)
682     : name_(name), begin_(begin), size_(size), base_begin_(base_begin), base_size_(base_size),
683       prot_(prot), reuse_(reuse), already_unmapped_(false), redzone_size_(redzone_size) {
684   if (size_ == 0) {
685     CHECK(begin_ == nullptr);
686     CHECK(base_begin_ == nullptr);
687     CHECK_EQ(base_size_, 0U);
688   } else {
689     CHECK(begin_ != nullptr);
690     CHECK(base_begin_ != nullptr);
691     CHECK_NE(base_size_, 0U);
692 
693     // Add it to gMaps.
694     std::lock_guard<std::mutex> mu(*mem_maps_lock_);
695     DCHECK(gMaps != nullptr);
696     gMaps->insert(std::make_pair(base_begin_, this));
697   }
698 }
699 
RemapAtEnd(uint8_t * new_end,const char * tail_name,int tail_prot,std::string * error_msg,bool use_debug_name)700 MemMap MemMap::RemapAtEnd(uint8_t* new_end,
701                           const char* tail_name,
702                           int tail_prot,
703                           std::string* error_msg,
704                           bool use_debug_name) {
705   return RemapAtEnd(new_end,
706                     tail_name,
707                     tail_prot,
708                     MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
709                     /* fd= */ -1,
710                     /* offset= */ 0,
711                     error_msg,
712                     use_debug_name);
713 }
714 
RemapAtEnd(uint8_t * new_end,const char * tail_name,int tail_prot,int flags,int fd,off_t offset,std::string * error_msg,bool use_debug_name)715 MemMap 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) {
723   DCHECK_GE(new_end, Begin());
724   DCHECK_LE(new_end, End());
725   DCHECK_LE(begin_ + size_, reinterpret_cast<uint8_t*>(base_begin_) + base_size_);
726   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);
730   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;
733   DCHECK_LE(new_base_end, old_base_end);
734   if (new_base_end == old_base_end) {
735     return Invalid();
736   }
737   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);
740   size_t tail_size = old_end - new_end;
741   uint8_t* tail_base_begin = new_base_end;
742   size_t tail_base_size = old_base_end - new_base_end;
743   DCHECK_EQ(tail_base_begin + tail_base_size, old_base_end);
744   DCHECK_ALIGNED(tail_base_size, kPageSize);
745 
746   MEMORY_TOOL_MAKE_UNDEFINED(tail_base_begin, tail_base_size);
747   // 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.
750   uint8_t* actual = reinterpret_cast<uint8_t*>(TargetMMap(tail_base_begin,
751                                                           tail_base_size,
752                                                           tail_prot,
753                                                           flags,
754                                                           fd,
755                                                           offset));
756   if (actual == MAP_FAILED) {
757     *error_msg = StringPrintf("map(%p, %zd, 0x%x, 0x%x, %d, 0) failed: %s. See process "
758                               "maps in the log.", tail_base_begin, tail_base_size, tail_prot, flags,
759                               fd, strerror(errno));
760     PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
761     return Invalid();
762   }
763   // 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   }
769 
770   if (use_debug_name) {
771     SetDebugName(actual, tail_name, tail_base_size);
772   }
773 
774   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);
778 }
779 
TakeReservedMemory(size_t byte_count)780 MemMap 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);
784   return MemMap(name_, begin, byte_count, begin, base_size, prot_, /* reuse= */ false);
785 }
786 
ReleaseReservedMemory(size_t byte_count)787 void 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);
809     auto node = gMaps->extract(it);
810     begin_ += byte_count;
811     size_ -= byte_count;
812     base_begin_ = begin_;
813     base_size_ = size_;
814     node.key() = base_begin_;
815     gMaps->insert(std::move(node));
816   }
817 }
818 
MadviseDontNeedAndZero()819 void MemMap::MadviseDontNeedAndZero() {
820   if (base_begin_ != nullptr || base_size_ != 0) {
821     if (!kMadviseZeroes) {
822       memset(base_begin_, 0, base_size_);
823     }
824 #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
828     int result = madvise(base_begin_, base_size_, MADV_DONTNEED);
829     if (result == -1) {
830       PLOG(WARNING) << "madvise failed";
831     }
832 #endif
833   }
834 }
835 
MadviseDontFork()836 int 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 
Sync()845 bool MemMap::Sync() {
846 #ifdef _WIN32
847   // TODO: add FlushViewOfFile support.
848   PLOG(ERROR) << "MemMap::Sync unsupported on Windows.";
849   return false;
850 #else
851   // 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;
856 #endif
857 }
858 
Protect(int prot)859 bool MemMap::Protect(int prot) {
860   if (base_begin_ == nullptr && base_size_ == 0) {
861     prot_ = prot;
862     return true;
863   }
864 
865 #ifndef _WIN32
866   if (mprotect(base_begin_, base_size_, prot) == 0) {
867     prot_ = prot;
868     return true;
869   }
870 #endif
871 
872   PLOG(ERROR) << "mprotect(" << reinterpret_cast<void*>(base_begin_) << ", " << base_size_ << ", "
873               << prot << ") failed";
874   return false;
875 }
876 
CheckNoGaps(MemMap & begin_map,MemMap & end_map)877 bool MemMap::CheckNoGaps(MemMap& begin_map, MemMap& end_map) {
878   std::lock_guard<std::mutex> mu(*mem_maps_lock_);
879   CHECK(begin_map.IsValid());
880   CHECK(end_map.IsValid());
881   CHECK(HasMemMap(begin_map));
882   CHECK(HasMemMap(end_map));
883   CHECK_LE(begin_map.BaseBegin(), end_map.BaseBegin());
884   MemMap* map = &begin_map;
885   while (map->BaseBegin() != end_map.BaseBegin()) {
886     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 
DumpMaps(std::ostream & os,bool terse)896 void MemMap::DumpMaps(std::ostream& os, bool terse) {
897   std::lock_guard<std::mutex> mu(*mem_maps_lock_);
898   DumpMapsLocked(os, terse);
899 }
900 
DumpMapsLocked(std::ostream & os,bool terse)901 void MemMap::DumpMapsLocked(std::ostream& os, bool terse) {
902   const auto& mem_maps = *gMaps;
903   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();
927     CHECK_ALIGNED(size, kPageSize);
928     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);
941         CHECK_ALIGNED(gap, kPageSize);
942         os << "~0x" << std::hex << (gap / kPageSize) << "P";
943         num = 0u;
944         size = 0u;
945       }
946       CHECK_ALIGNED(it->second->BaseSize(), kPageSize);
947       ++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   }
958 }
959 
HasMemMap(MemMap & map)960 bool MemMap::HasMemMap(MemMap& map) {
961   void* base_begin = map.BaseBegin();
962   for (auto it = gMaps->lower_bound(base_begin), end = gMaps->end();
963        it != end && it->first == base_begin; ++it) {
964     if (it->second == &map) {
965       return true;
966     }
967   }
968   return false;
969 }
970 
GetLargestMemMapAt(void * address)971 MemMap* MemMap::GetLargestMemMapAt(void* address) {
972   size_t largest_size = 0;
973   MemMap* largest_map = nullptr;
974   DCHECK(gMaps != nullptr);
975   for (auto it = gMaps->lower_bound(address), end = gMaps->end();
976        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 
Init()987 void MemMap::Init() {
988   if (mem_maps_lock_ != nullptr) {
989     // dex2oat calls MemMap::Init twice since its needed before the runtime is created.
990     return;
991   }
992   mem_maps_lock_ = new std::mutex();
993   // Not for thread safety, but for the annotation that gMaps is GUARDED_BY(mem_maps_lock_).
994   std::lock_guard<std::mutex> mu(*mem_maps_lock_);
995   DCHECK(gMaps == nullptr);
996   gMaps = new Maps;
997 
998   TargetMMapInit();
999 }
1000 
Shutdown()1001 void MemMap::Shutdown() {
1002   if (mem_maps_lock_ == nullptr) {
1003     // If MemMap::Shutdown is called more than once, there is no effect.
1004     return;
1005   }
1006   {
1007     // Not for thread safety, but for the annotation that gMaps is GUARDED_BY(mem_maps_lock_).
1008     std::lock_guard<std::mutex> mu(*mem_maps_lock_);
1009     DCHECK(gMaps != nullptr);
1010     delete gMaps;
1011     gMaps = nullptr;
1012   }
1013   delete mem_maps_lock_;
1014   mem_maps_lock_ = nullptr;
1015 }
1016 
SetSize(size_t new_size)1017 void MemMap::SetSize(size_t new_size) {
1018   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;
1023     return;
1024   }
1025   CHECK_LT(new_base_size, base_size_);
1026   MEMORY_TOOL_MAKE_UNDEFINED(
1027       reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(BaseBegin()) +
1028                               new_base_size),
1029       base_size_ - new_base_size);
1030   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_;
1034   base_size_ = new_base_size;
1035   size_ = new_size;
1036 }
1037 
MapInternalArtLow4GBAllocator(size_t length,int prot,int flags,int fd,off_t offset)1038 void* 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 
MapInternal(void * addr,size_t length,int prot,int flags,int fd,off_t offset,bool low_4gb)1131 void* 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__
1139   // 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);
1155   // 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) {
1162     // 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);
1170 
1171     if (actual == MAP_FAILED) {
1172       return MAP_FAILED;
1173     }
1174 
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;
1179         TargetMUnmap(actual, length);
1180         errno = ENOMEM;
1181         return MAP_FAILED;
1182       }
1183     }
1184     return actual;
1185   }
1186 
1187   actual = TargetMMap(addr, length, prot, flags, fd, offset);
1188 #else
1189 #if defined(__LP64__)
1190   if (low_4gb && addr == nullptr) {
1191     flags |= MAP_32BIT;
1192   }
1193 #endif
1194   actual = TargetMMap(addr, length, prot, flags, fd, offset);
1195 #endif
1196   return actual;
1197 }
1198 
operator <<(std::ostream & os,const MemMap & mem_map)1199 std::ostream& operator<<(std::ostream& os, const MemMap& mem_map) {
1200   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());
1203   return os;
1204 }
1205 
TryReadable()1206 void 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 
ZeroAndReleasePages(void * address,size_t length)1224 void ZeroAndReleasePages(void* address, size_t length) {
1225   if (length == 0) {
1226     return;
1227   }
1228   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);
1241 #ifdef _WIN32
1242     LOG(WARNING) << "ZeroAndReleasePages does not madvise on Windows.";
1243 #else
1244     CHECK_NE(madvise(page_begin, page_end - page_begin, MADV_DONTNEED), -1) << "madvise failed";
1245 #endif
1246     std::fill(page_end, mem_end, 0);
1247   }
1248 }
1249 
AlignBy(size_t size)1250 void 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);
1255   CHECK(!reuse_);
1256   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);
1275     CHECK_EQ(TargetMUnmap(base_begin, aligned_base_begin - base_begin), 0)
1276         << "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);
1281     CHECK_EQ(TargetMUnmap(aligned_base_end, base_end - aligned_base_end), 0)
1282         << "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_);
1286   if (base_begin < aligned_base_begin) {
1287     auto it = GetGMapsEntry(*this);
1288     auto node = gMaps->extract(it);
1289     node.key() = aligned_base_begin;
1290     gMaps->insert(std::move(node));
1291   }
1292   base_begin_ = aligned_base_begin;
1293   base_size_ = aligned_base_size;
1294   begin_ = aligned_base_begin;
1295   size_ = aligned_base_size;
1296   DCHECK(gMaps != nullptr);
1297 }
1298 
1299 }  // namespace art
1300