1 /*
2  * Copyright (C) 2013 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 "arena_allocator-inl.h"
18 
19 
20 #include <algorithm>
21 #include <cstddef>
22 #include <iomanip>
23 #include <numeric>
24 
25 #include <android-base/logging.h>
26 
27 #include "mman.h"
28 
29 namespace art {
30 
31 constexpr size_t kMemoryToolRedZoneBytes = 8;
32 
33 template <bool kCount>
34 const char* const ArenaAllocatorStatsImpl<kCount>::kAllocNames[] = {
35   // Every name should have the same width and end with a space. Abbreviate if necessary:
36   "Misc         ",
37   "SwitchTbl    ",
38   "SlowPaths    ",
39   "GrowBitMap   ",
40   "STL          ",
41   "GraphBuilder ",
42   "Graph        ",
43   "BasicBlock   ",
44   "BlockList    ",
45   "RevPostOrder ",
46   "LinearOrder  ",
47   "Reachability ",
48   "ConstantsMap ",
49   "Predecessors ",
50   "Successors   ",
51   "Dominated    ",
52   "Instruction  ",
53   "CtorFenceIns ",
54   "InvokeInputs ",
55   "PhiInputs    ",
56   "TypeCheckIns ",
57   "LoopInfo     ",
58   "LIBackEdges  ",
59   "TryCatchInf  ",
60   "UseListNode  ",
61   "Environment  ",
62   "EnvVRegs     ",
63   "EnvLocations ",
64   "LocSummary   ",
65   "SsaBuilder   ",
66   "MoveOperands ",
67   "CodeBuffer   ",
68   "StackMaps    ",
69   "Optimization ",
70   "GVN          ",
71   "InductionVar ",
72   "BCE          ",
73   "DCE          ",
74   "LSA          ",
75   "LSE          ",
76   "CFRE         ",
77   "LICM         ",
78   "LoopOpt      ",
79   "SsaLiveness  ",
80   "SsaPhiElim   ",
81   "RefTypeProp  ",
82   "SelectGen    ",
83   "SideEffects  ",
84   "RegAllocator ",
85   "RegAllocVldt ",
86   "StackMapStm  ",
87   "BitTableBld  ",
88   "VectorNode   ",
89   "CodeGen      ",
90   "Assembler    ",
91   "ParallelMove ",
92   "GraphChecker ",
93   "Verifier     ",
94   "CallingConv  ",
95   "CHA          ",
96   "Scheduler    ",
97   "Profile      ",
98   "SBCloner     ",
99 };
100 
101 template <bool kCount>
ArenaAllocatorStatsImpl()102 ArenaAllocatorStatsImpl<kCount>::ArenaAllocatorStatsImpl()
103     : num_allocations_(0u),
104       alloc_stats_(kNumArenaAllocKinds, 0u) {
105 }
106 
107 template <bool kCount>
Copy(const ArenaAllocatorStatsImpl & other)108 void ArenaAllocatorStatsImpl<kCount>::Copy(const ArenaAllocatorStatsImpl& other) {
109   num_allocations_ = other.num_allocations_;
110   std::copy_n(other.alloc_stats_.begin(), kNumArenaAllocKinds, alloc_stats_.begin());
111 }
112 
113 template <bool kCount>
RecordAlloc(size_t bytes,ArenaAllocKind kind)114 void ArenaAllocatorStatsImpl<kCount>::RecordAlloc(size_t bytes, ArenaAllocKind kind) {
115   alloc_stats_[kind] += bytes;
116   ++num_allocations_;
117 }
118 
119 template <bool kCount>
NumAllocations() const120 size_t ArenaAllocatorStatsImpl<kCount>::NumAllocations() const {
121   return num_allocations_;
122 }
123 
124 template <bool kCount>
BytesAllocated() const125 size_t ArenaAllocatorStatsImpl<kCount>::BytesAllocated() const {
126   const size_t init = 0u;  // Initial value of the correct type.
127   return std::accumulate(alloc_stats_.begin(), alloc_stats_.end(), init);
128 }
129 
130 template <bool kCount>
Dump(std::ostream & os,const Arena * first,ssize_t lost_bytes_adjustment) const131 void ArenaAllocatorStatsImpl<kCount>::Dump(std::ostream& os, const Arena* first,
132                                            ssize_t lost_bytes_adjustment) const {
133   size_t malloc_bytes = 0u;
134   size_t lost_bytes = 0u;
135   size_t num_arenas = 0u;
136   for (const Arena* arena = first; arena != nullptr; arena = arena->next_) {
137     malloc_bytes += arena->Size();
138     lost_bytes += arena->RemainingSpace();
139     ++num_arenas;
140   }
141   // The lost_bytes_adjustment is used to make up for the fact that the current arena
142   // may not have the bytes_allocated_ updated correctly.
143   lost_bytes += lost_bytes_adjustment;
144   const size_t bytes_allocated = BytesAllocated();
145   os << " MEM: used: " << bytes_allocated << ", allocated: " << malloc_bytes
146      << ", lost: " << lost_bytes << "\n";
147   size_t num_allocations = NumAllocations();
148   if (num_allocations != 0) {
149     os << "Number of arenas allocated: " << num_arenas << ", Number of allocations: "
150        << num_allocations << ", avg size: " << bytes_allocated / num_allocations << "\n";
151   }
152   os << "===== Allocation by kind\n";
153   static_assert(arraysize(kAllocNames) == kNumArenaAllocKinds, "arraysize of kAllocNames");
154   for (int i = 0; i < kNumArenaAllocKinds; i++) {
155     // Reduce output by listing only allocation kinds that actually have allocations.
156     if (alloc_stats_[i] != 0u) {
157       os << kAllocNames[i] << std::setw(10) << alloc_stats_[i] << "\n";
158     }
159   }
160 }
161 
162 #pragma GCC diagnostic push
163 #if __clang_major__ >= 4
164 #pragma GCC diagnostic ignored "-Winstantiation-after-specialization"
165 #endif
166 // We're going to use ArenaAllocatorStatsImpl<kArenaAllocatorCountAllocations> which needs
167 // to be explicitly instantiated if kArenaAllocatorCountAllocations is true. Explicit
168 // instantiation of the specialization ArenaAllocatorStatsImpl<false> does not do anything
169 // but requires the warning "-Winstantiation-after-specialization" to be turned off.
170 //
171 // To avoid bit-rot of the ArenaAllocatorStatsImpl<true>, instantiate it also in debug builds
172 // (but keep the unnecessary code out of release builds) as we do not usually compile with
173 // kArenaAllocatorCountAllocations set to true.
174 template class ArenaAllocatorStatsImpl<kArenaAllocatorCountAllocations || kIsDebugBuild>;
175 #pragma GCC diagnostic pop
176 
DoMakeDefined(void * ptr,size_t size)177 void ArenaAllocatorMemoryTool::DoMakeDefined(void* ptr, size_t size) {
178   MEMORY_TOOL_MAKE_DEFINED(ptr, size);
179 }
180 
DoMakeUndefined(void * ptr,size_t size)181 void ArenaAllocatorMemoryTool::DoMakeUndefined(void* ptr, size_t size) {
182   MEMORY_TOOL_MAKE_UNDEFINED(ptr, size);
183 }
184 
DoMakeInaccessible(void * ptr,size_t size)185 void ArenaAllocatorMemoryTool::DoMakeInaccessible(void* ptr, size_t size) {
186   MEMORY_TOOL_MAKE_NOACCESS(ptr, size);
187 }
188 
Arena()189 Arena::Arena() : bytes_allocated_(0), memory_(nullptr), size_(0), next_(nullptr) {
190 }
191 
BytesAllocated() const192 size_t ArenaAllocator::BytesAllocated() const {
193   return ArenaAllocatorStats::BytesAllocated();
194 }
195 
BytesUsed() const196 size_t ArenaAllocator::BytesUsed() const {
197   size_t total = ptr_ - begin_;
198   if (arena_head_ != nullptr) {
199     for (Arena* cur_arena = arena_head_->next_; cur_arena != nullptr;
200          cur_arena = cur_arena->next_) {
201      total += cur_arena->GetBytesAllocated();
202     }
203   }
204   return total;
205 }
206 
ArenaAllocator(ArenaPool * pool)207 ArenaAllocator::ArenaAllocator(ArenaPool* pool)
208   : pool_(pool),
209     begin_(nullptr),
210     end_(nullptr),
211     ptr_(nullptr),
212     arena_head_(nullptr) {
213 }
214 
UpdateBytesAllocated()215 void ArenaAllocator::UpdateBytesAllocated() {
216   if (arena_head_ != nullptr) {
217     // Update how many bytes we have allocated into the arena so that the arena pool knows how
218     // much memory to zero out.
219     arena_head_->bytes_allocated_ = ptr_ - begin_;
220   }
221 }
222 
AllocWithMemoryTool(size_t bytes,ArenaAllocKind kind)223 void* ArenaAllocator::AllocWithMemoryTool(size_t bytes, ArenaAllocKind kind) {
224   // We mark all memory for a newly retrieved arena as inaccessible and then
225   // mark only the actually allocated memory as defined. That leaves red zones
226   // and padding between allocations marked as inaccessible.
227   size_t rounded_bytes = RoundUp(bytes + kMemoryToolRedZoneBytes, 8);
228   ArenaAllocatorStats::RecordAlloc(rounded_bytes, kind);
229   uint8_t* ret;
230   if (UNLIKELY(rounded_bytes > static_cast<size_t>(end_ - ptr_))) {
231     ret = AllocFromNewArenaWithMemoryTool(rounded_bytes);
232   } else {
233     ret = ptr_;
234     ptr_ += rounded_bytes;
235   }
236   MEMORY_TOOL_MAKE_DEFINED(ret, bytes);
237   // Check that the memory is already zeroed out.
238   DCHECK(std::all_of(ret, ret + bytes, [](uint8_t val) { return val == 0u; }));
239   return ret;
240 }
241 
AllocWithMemoryToolAlign16(size_t bytes,ArenaAllocKind kind)242 void* ArenaAllocator::AllocWithMemoryToolAlign16(size_t bytes, ArenaAllocKind kind) {
243   // We mark all memory for a newly retrieved arena as inaccessible and then
244   // mark only the actually allocated memory as defined. That leaves red zones
245   // and padding between allocations marked as inaccessible.
246   size_t rounded_bytes = bytes + kMemoryToolRedZoneBytes;
247   DCHECK_ALIGNED(rounded_bytes, 8);  // `bytes` is 16-byte aligned, red zone is 8-byte aligned.
248   uintptr_t padding =
249       ((reinterpret_cast<uintptr_t>(ptr_) + 15u) & 15u) - reinterpret_cast<uintptr_t>(ptr_);
250   ArenaAllocatorStats::RecordAlloc(rounded_bytes, kind);
251   uint8_t* ret;
252   if (UNLIKELY(padding + rounded_bytes > static_cast<size_t>(end_ - ptr_))) {
253     static_assert(kArenaAlignment >= 16, "Expecting sufficient alignment for new Arena.");
254     ret = AllocFromNewArenaWithMemoryTool(rounded_bytes);
255   } else {
256     ptr_ += padding;  // Leave padding inaccessible.
257     ret = ptr_;
258     ptr_ += rounded_bytes;
259   }
260   MEMORY_TOOL_MAKE_DEFINED(ret, bytes);
261   // Check that the memory is already zeroed out.
262   DCHECK(std::all_of(ret, ret + bytes, [](uint8_t val) { return val == 0u; }));
263   return ret;
264 }
265 
~ArenaAllocator()266 ArenaAllocator::~ArenaAllocator() {
267   // Reclaim all the arenas by giving them back to the thread pool.
268   UpdateBytesAllocated();
269   pool_->FreeArenaChain(arena_head_);
270 }
271 
AllocFromNewArena(size_t bytes)272 uint8_t* ArenaAllocator::AllocFromNewArena(size_t bytes) {
273   Arena* new_arena = pool_->AllocArena(std::max(arena_allocator::kArenaDefaultSize, bytes));
274   DCHECK(new_arena != nullptr);
275   DCHECK_LE(bytes, new_arena->Size());
276   if (static_cast<size_t>(end_ - ptr_) > new_arena->Size() - bytes) {
277     // The old arena has more space remaining than the new one, so keep using it.
278     // This can happen when the requested size is over half of the default size.
279     DCHECK(arena_head_ != nullptr);
280     new_arena->bytes_allocated_ = bytes;  // UpdateBytesAllocated() on the new_arena.
281     new_arena->next_ = arena_head_->next_;
282     arena_head_->next_ = new_arena;
283   } else {
284     UpdateBytesAllocated();
285     new_arena->next_ = arena_head_;
286     arena_head_ = new_arena;
287     // Update our internal data structures.
288     begin_ = new_arena->Begin();
289     DCHECK_ALIGNED(begin_, kAlignment);
290     ptr_ = begin_ + bytes;
291     end_ = new_arena->End();
292   }
293   return new_arena->Begin();
294 }
295 
AllocFromNewArenaWithMemoryTool(size_t bytes)296 uint8_t* ArenaAllocator::AllocFromNewArenaWithMemoryTool(size_t bytes) {
297   uint8_t* ret = AllocFromNewArena(bytes);
298   uint8_t* noaccess_begin = ret + bytes;
299   uint8_t* noaccess_end;
300   if (ret == arena_head_->Begin()) {
301     DCHECK(ptr_ - bytes == ret);
302     noaccess_end = end_;
303   } else {
304     // We're still using the old arena but `ret` comes from a new one just after it.
305     DCHECK(arena_head_->next_ != nullptr);
306     DCHECK(ret == arena_head_->next_->Begin());
307     DCHECK_EQ(bytes, arena_head_->next_->GetBytesAllocated());
308     noaccess_end = arena_head_->next_->End();
309   }
310   MEMORY_TOOL_MAKE_NOACCESS(noaccess_begin, noaccess_end - noaccess_begin);
311   return ret;
312 }
313 
Contains(const void * ptr) const314 bool ArenaAllocator::Contains(const void* ptr) const {
315   if (ptr >= begin_ && ptr < end_) {
316     return true;
317   }
318   for (const Arena* cur_arena = arena_head_; cur_arena != nullptr; cur_arena = cur_arena->next_) {
319     if (cur_arena->Contains(ptr)) {
320       return true;
321     }
322   }
323   return false;
324 }
325 
MemStats(const char * name,const ArenaAllocatorStats * stats,const Arena * first_arena,ssize_t lost_bytes_adjustment)326 MemStats::MemStats(const char* name,
327                    const ArenaAllocatorStats* stats,
328                    const Arena* first_arena,
329                    ssize_t lost_bytes_adjustment)
330     : name_(name),
331       stats_(stats),
332       first_arena_(first_arena),
333       lost_bytes_adjustment_(lost_bytes_adjustment) {
334 }
335 
Dump(std::ostream & os) const336 void MemStats::Dump(std::ostream& os) const {
337   os << name_ << " stats:\n";
338   stats_->Dump(os, first_arena_, lost_bytes_adjustment_);
339 }
340 
341 // Dump memory usage stats.
GetMemStats() const342 MemStats ArenaAllocator::GetMemStats() const {
343   ssize_t lost_bytes_adjustment =
344       (arena_head_ == nullptr) ? 0 : (end_ - ptr_) - arena_head_->RemainingSpace();
345   return MemStats("ArenaAllocator", this, arena_head_, lost_bytes_adjustment);
346 }
347 
348 }  // namespace art
349