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 #ifndef ART_RUNTIME_MEM_MAP_H_
18 #define ART_RUNTIME_MEM_MAP_H_
19 
20 #include <stddef.h>
21 #include <sys/types.h>
22 
23 #include <map>
24 #include <mutex>
25 #include <string>
26 
27 #include "android-base/thread_annotations.h"
28 
29 namespace art {
30 
31 #if defined(__LP64__) && (!defined(__x86_64__) || defined(__APPLE__))
32 #define USE_ART_LOW_4G_ALLOCATOR 1
33 #else
34 #define USE_ART_LOW_4G_ALLOCATOR 0
35 #endif
36 
37 #ifdef __linux__
38 static constexpr bool kMadviseZeroes = true;
39 #else
40 static constexpr bool kMadviseZeroes = false;
41 #endif
42 
43 // Used to keep track of mmap segments.
44 //
45 // On 64b systems not supporting MAP_32BIT, the implementation of MemMap will do a linear scan
46 // for free pages. For security, the start of this scan should be randomized. This requires a
47 // dynamic initializer.
48 // For this to work, it is paramount that there are no other static initializers that access MemMap.
49 // Otherwise, calls might see uninitialized values.
50 class MemMap {
51  public:
52   // Request an anonymous region of length 'byte_count' and a requested base address.
53   // Use null as the requested base address if you don't care.
54   // "reuse" allows re-mapping an address range from an existing mapping.
55   //
56   // The word "anonymous" in this context means "not backed by a file". The supplied
57   // 'name' will be used -- on systems that support it -- to give the mapping
58   // a name.
59   //
60   // On success, returns returns a MemMap instance.  On failure, returns null.
61   static MemMap* MapAnonymous(const char* name,
62                               uint8_t* addr,
63                               size_t byte_count,
64                               int prot,
65                               bool low_4gb,
66                               bool reuse,
67                               std::string* error_msg,
68                               bool use_ashmem = true);
69 
70   // Create placeholder for a region allocated by direct call to mmap.
71   // This is useful when we do not have control over the code calling mmap,
72   // but when we still want to keep track of it in the list.
73   // The region is not considered to be owned and will not be unmmaped.
74   static MemMap* MapDummy(const char* name, uint8_t* addr, size_t byte_count);
75 
76   // Map part of a file, taking care of non-page aligned offsets.  The
77   // "start" offset is absolute, not relative.
78   //
79   // On success, returns returns a MemMap instance.  On failure, returns null.
MapFile(size_t byte_count,int prot,int flags,int fd,off_t start,bool low_4gb,const char * filename,std::string * error_msg)80   static MemMap* MapFile(size_t byte_count,
81                          int prot,
82                          int flags,
83                          int fd,
84                          off_t start,
85                          bool low_4gb,
86                          const char* filename,
87                          std::string* error_msg) {
88     return MapFileAtAddress(nullptr,
89                             byte_count,
90                             prot,
91                             flags,
92                             fd,
93                             start,
94                             /*low_4gb*/low_4gb,
95                             /*reuse*/false,
96                             filename,
97                             error_msg);
98   }
99 
100   // Map part of a file, taking care of non-page aligned offsets.  The "start" offset is absolute,
101   // not relative. This version allows requesting a specific address for the base of the mapping.
102   // "reuse" allows us to create a view into an existing mapping where we do not take ownership of
103   // the memory. If error_msg is null then we do not print /proc/maps to the log if
104   // MapFileAtAddress fails. This helps improve performance of the fail case since reading and
105   // printing /proc/maps takes several milliseconds in the worst case.
106   //
107   // On success, returns returns a MemMap instance.  On failure, returns null.
108   static MemMap* MapFileAtAddress(uint8_t* addr,
109                                   size_t byte_count,
110                                   int prot,
111                                   int flags,
112                                   int fd,
113                                   off_t start,
114                                   bool low_4gb,
115                                   bool reuse,
116                                   const char* filename,
117                                   std::string* error_msg);
118 
119   // Releases the memory mapping.
120   ~MemMap() REQUIRES(!MemMap::mem_maps_lock_);
121 
GetName()122   const std::string& GetName() const {
123     return name_;
124   }
125 
126   bool Sync();
127 
128   bool Protect(int prot);
129 
130   void MadviseDontNeedAndZero();
131 
GetProtect()132   int GetProtect() const {
133     return prot_;
134   }
135 
Begin()136   uint8_t* Begin() const {
137     return begin_;
138   }
139 
Size()140   size_t Size() const {
141     return size_;
142   }
143 
144   // Resize the mem-map by unmapping pages at the end. Currently only supports shrinking.
145   void SetSize(size_t new_size);
146 
End()147   uint8_t* End() const {
148     return Begin() + Size();
149   }
150 
BaseBegin()151   void* BaseBegin() const {
152     return base_begin_;
153   }
154 
BaseSize()155   size_t BaseSize() const {
156     return base_size_;
157   }
158 
BaseEnd()159   void* BaseEnd() const {
160     return reinterpret_cast<uint8_t*>(BaseBegin()) + BaseSize();
161   }
162 
HasAddress(const void * addr)163   bool HasAddress(const void* addr) const {
164     return Begin() <= addr && addr < End();
165   }
166 
167   // Unmap the pages at end and remap them to create another memory map.
168   MemMap* RemapAtEnd(uint8_t* new_end,
169                      const char* tail_name,
170                      int tail_prot,
171                      std::string* error_msg,
172                      bool use_ashmem = true);
173 
174   static bool CheckNoGaps(MemMap* begin_map, MemMap* end_map)
175       REQUIRES(!MemMap::mem_maps_lock_);
176   static void DumpMaps(std::ostream& os, bool terse = false)
177       REQUIRES(!MemMap::mem_maps_lock_);
178 
179   // Init and Shutdown are NOT thread safe.
180   // Both may be called multiple times and MemMap objects may be created any
181   // time after the first call to Init and before the first call to Shutodwn.
182   static void Init() REQUIRES(!MemMap::mem_maps_lock_);
183   static void Shutdown() REQUIRES(!MemMap::mem_maps_lock_);
184 
185   // If the map is PROT_READ, try to read each page of the map to check it is in fact readable (not
186   // faulting). This is used to diagnose a bug b/19894268 where mprotect doesn't seem to be working
187   // intermittently.
188   void TryReadable();
189 
190   // Align the map by unmapping the unaligned parts at the lower and the higher ends.
191   void AlignBy(size_t size);
192 
193   // For annotation reasons.
GetMemMapsLock()194   static std::mutex* GetMemMapsLock() RETURN_CAPABILITY(mem_maps_lock_) {
195     return nullptr;
196   }
197 
198  private:
199   MemMap(const std::string& name,
200          uint8_t* begin,
201          size_t size,
202          void* base_begin,
203          size_t base_size,
204          int prot,
205          bool reuse,
206          size_t redzone_size = 0) REQUIRES(!MemMap::mem_maps_lock_);
207 
208   static void DumpMapsLocked(std::ostream& os, bool terse)
209       REQUIRES(MemMap::mem_maps_lock_);
210   static bool HasMemMap(MemMap* map)
211       REQUIRES(MemMap::mem_maps_lock_);
212   static MemMap* GetLargestMemMapAt(void* address)
213       REQUIRES(MemMap::mem_maps_lock_);
214   static bool ContainedWithinExistingMap(uint8_t* ptr, size_t size, std::string* error_msg)
215       REQUIRES(!MemMap::mem_maps_lock_);
216 
217   // Internal version of mmap that supports low 4gb emulation.
218   static void* MapInternal(void* addr,
219                            size_t length,
220                            int prot,
221                            int flags,
222                            int fd,
223                            off_t offset,
224                            bool low_4gb);
225 
226   const std::string name_;
227   uint8_t* begin_;  // Start of data. May be changed by AlignBy.
228   size_t size_;  // Length of data.
229 
230   void* base_begin_;  // Page-aligned base address. May be changed by AlignBy.
231   size_t base_size_;  // Length of mapping. May be changed by RemapAtEnd (ie Zygote).
232   int prot_;  // Protection of the map.
233 
234   // When reuse_ is true, this is just a view of an existing mapping
235   // and we do not take ownership and are not responsible for
236   // unmapping.
237   const bool reuse_;
238 
239   const size_t redzone_size_;
240 
241 #if USE_ART_LOW_4G_ALLOCATOR
242   static uintptr_t next_mem_pos_;   // Next memory location to check for low_4g extent.
243 #endif
244 
245   static std::mutex* mem_maps_lock_;
246 
247   friend class MemMapTest;  // To allow access to base_begin_ and base_size_.
248 };
249 
250 std::ostream& operator<<(std::ostream& os, const MemMap& mem_map);
251 
252 // Zero and release pages if possible, no requirements on alignments.
253 void ZeroAndReleasePages(void* address, size_t length);
254 
255 }  // namespace art
256 
257 #endif  // ART_RUNTIME_MEM_MAP_H_
258