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_GC_HEAP_H_
18 #define ART_RUNTIME_GC_HEAP_H_
19 
20 #include <iosfwd>
21 #include <string>
22 #include <unordered_set>
23 #include <vector>
24 
25 #include <android-base/logging.h>
26 
27 #include "allocator_type.h"
28 #include "base/atomic.h"
29 #include "base/histogram.h"
30 #include "base/macros.h"
31 #include "base/mutex.h"
32 #include "base/runtime_debug.h"
33 #include "base/safe_map.h"
34 #include "base/time_utils.h"
35 #include "gc/collector/gc_type.h"
36 #include "gc/collector/iteration.h"
37 #include "gc/collector_type.h"
38 #include "gc/gc_cause.h"
39 #include "gc/space/large_object_space.h"
40 #include "handle.h"
41 #include "obj_ptr.h"
42 #include "offsets.h"
43 #include "process_state.h"
44 #include "read_barrier_config.h"
45 #include "runtime_globals.h"
46 #include "verify_object.h"
47 
48 namespace art {
49 
50 class ConditionVariable;
51 enum class InstructionSet;
52 class IsMarkedVisitor;
53 class Mutex;
54 class ReflectiveValueVisitor;
55 class RootVisitor;
56 class StackVisitor;
57 class Thread;
58 class ThreadPool;
59 class TimingLogger;
60 class VariableSizedHandleScope;
61 
62 namespace mirror {
63 class Class;
64 class Object;
65 }  // namespace mirror
66 
67 namespace gc {
68 
69 class AllocationListener;
70 class AllocRecordObjectMap;
71 class GcPauseListener;
72 class HeapTask;
73 class ReferenceProcessor;
74 class TaskProcessor;
75 class Verification;
76 
77 namespace accounting {
78 template <typename T> class AtomicStack;
79 typedef AtomicStack<mirror::Object> ObjectStack;
80 class CardTable;
81 class HeapBitmap;
82 class ModUnionTable;
83 class ReadBarrierTable;
84 class RememberedSet;
85 }  // namespace accounting
86 
87 namespace collector {
88 class ConcurrentCopying;
89 class GarbageCollector;
90 class MarkSweep;
91 class SemiSpace;
92 }  // namespace collector
93 
94 namespace allocator {
95 class RosAlloc;
96 }  // namespace allocator
97 
98 namespace space {
99 class AllocSpace;
100 class BumpPointerSpace;
101 class ContinuousMemMapAllocSpace;
102 class DiscontinuousSpace;
103 class DlMallocSpace;
104 class ImageSpace;
105 class LargeObjectSpace;
106 class MallocSpace;
107 class RegionSpace;
108 class RosAllocSpace;
109 class Space;
110 class ZygoteSpace;
111 }  // namespace space
112 
113 enum HomogeneousSpaceCompactResult {
114   // Success.
115   kSuccess,
116   // Reject due to disabled moving GC.
117   kErrorReject,
118   // Unsupported due to the current configuration.
119   kErrorUnsupported,
120   // System is shutting down.
121   kErrorVMShuttingDown,
122 };
123 
124 // If true, use rosalloc/RosAllocSpace instead of dlmalloc/DlMallocSpace
125 static constexpr bool kUseRosAlloc = true;
126 
127 // If true, use thread-local allocation stack.
128 static constexpr bool kUseThreadLocalAllocationStack = true;
129 
130 class Heap {
131  public:
132   // How much we grow the TLAB if we can do it.
133   static constexpr size_t kPartialTlabSize = 16 * KB;
134   static constexpr bool kUsePartialTlabs = true;
135 
136   static constexpr size_t kDefaultStartingSize = kPageSize;
137   static constexpr size_t kDefaultInitialSize = 2 * MB;
138   static constexpr size_t kDefaultMaximumSize = 256 * MB;
139   static constexpr size_t kDefaultNonMovingSpaceCapacity = 64 * MB;
140   static constexpr size_t kDefaultMaxFree = 2 * MB;
141   static constexpr size_t kDefaultMinFree = kDefaultMaxFree / 4;
142   static constexpr size_t kDefaultLongPauseLogThreshold = MsToNs(5);
143   static constexpr size_t kDefaultLongGCLogThreshold = MsToNs(100);
144   static constexpr size_t kDefaultTLABSize = 32 * KB;
145   static constexpr double kDefaultTargetUtilization = 0.75;
146   static constexpr double kDefaultHeapGrowthMultiplier = 2.0;
147   // Primitive arrays larger than this size are put in the large object space.
148   static constexpr size_t kMinLargeObjectThreshold = 3 * kPageSize;
149   static constexpr size_t kDefaultLargeObjectThreshold = kMinLargeObjectThreshold;
150   // Whether or not parallel GC is enabled. If not, then we never create the thread pool.
151   static constexpr bool kDefaultEnableParallelGC = false;
152   static uint8_t* const kPreferredAllocSpaceBegin;
153 
154   // Whether or not we use the free list large object space. Only use it if USE_ART_LOW_4G_ALLOCATOR
155   // since this means that we have to use the slow msync loop in MemMap::MapAnonymous.
156   static constexpr space::LargeObjectSpaceType kDefaultLargeObjectSpaceType =
157       USE_ART_LOW_4G_ALLOCATOR ?
158           space::LargeObjectSpaceType::kFreeList
159         : space::LargeObjectSpaceType::kMap;
160 
161   // Used so that we don't overflow the allocation time atomic integer.
162   static constexpr size_t kTimeAdjust = 1024;
163 
164   // Client should call NotifyNativeAllocation every kNotifyNativeInterval allocations.
165   // Should be chosen so that time_to_call_mallinfo / kNotifyNativeInterval is on the same order
166   // as object allocation time. time_to_call_mallinfo seems to be on the order of 1 usec
167   // on Android.
168 #ifdef __ANDROID__
169   static constexpr uint32_t kNotifyNativeInterval = 32;
170 #else
171   // Some host mallinfo() implementations are slow. And memory is less scarce.
172   static constexpr uint32_t kNotifyNativeInterval = 384;
173 #endif
174 
175   // RegisterNativeAllocation checks immediately whether GC is needed if size exceeds the
176   // following. kCheckImmediatelyThreshold * kNotifyNativeInterval should be small enough to
177   // make it safe to allocate that many bytes between checks.
178   static constexpr size_t kCheckImmediatelyThreshold = 300000;
179 
180   // How often we allow heap trimming to happen (nanoseconds).
181   static constexpr uint64_t kHeapTrimWait = MsToNs(5000);
182   // How long we wait after a transition request to perform a collector transition (nanoseconds).
183   static constexpr uint64_t kCollectorTransitionWait = MsToNs(5000);
184   // Whether the transition-wait applies or not. Zero wait will stress the
185   // transition code and collector, but increases jank probability.
186   DECLARE_RUNTIME_DEBUG_FLAG(kStressCollectorTransition);
187 
188   // Create a heap with the requested sizes. The possible empty
189   // image_file_names names specify Spaces to load based on
190   // ImageWriter output.
191   Heap(size_t initial_size,
192        size_t growth_limit,
193        size_t min_free,
194        size_t max_free,
195        double target_utilization,
196        double foreground_heap_growth_multiplier,
197        size_t stop_for_native_allocs,
198        size_t capacity,
199        size_t non_moving_space_capacity,
200        const std::vector<std::string>& boot_class_path,
201        const std::vector<std::string>& boot_class_path_locations,
202        const std::string& image_file_name,
203        InstructionSet image_instruction_set,
204        CollectorType foreground_collector_type,
205        CollectorType background_collector_type,
206        space::LargeObjectSpaceType large_object_space_type,
207        size_t large_object_threshold,
208        size_t parallel_gc_threads,
209        size_t conc_gc_threads,
210        bool low_memory_mode,
211        size_t long_pause_threshold,
212        size_t long_gc_threshold,
213        bool ignore_target_footprint,
214        bool always_log_explicit_gcs,
215        bool use_tlab,
216        bool verify_pre_gc_heap,
217        bool verify_pre_sweeping_heap,
218        bool verify_post_gc_heap,
219        bool verify_pre_gc_rosalloc,
220        bool verify_pre_sweeping_rosalloc,
221        bool verify_post_gc_rosalloc,
222        bool gc_stress_mode,
223        bool measure_gc_performance,
224        bool use_homogeneous_space_compaction,
225        bool use_generational_cc,
226        uint64_t min_interval_homogeneous_space_compaction_by_oom,
227        bool dump_region_info_before_gc,
228        bool dump_region_info_after_gc);
229 
230   ~Heap();
231 
232   // Allocates and initializes storage for an object instance.
233   template <bool kInstrumented = true, typename PreFenceVisitor>
AllocObject(Thread * self,ObjPtr<mirror::Class> klass,size_t num_bytes,const PreFenceVisitor & pre_fence_visitor)234   mirror::Object* AllocObject(Thread* self,
235                               ObjPtr<mirror::Class> klass,
236                               size_t num_bytes,
237                               const PreFenceVisitor& pre_fence_visitor)
238       REQUIRES_SHARED(Locks::mutator_lock_)
239       REQUIRES(!*gc_complete_lock_,
240                !*pending_task_lock_,
241                !*backtrace_lock_,
242                !process_state_update_lock_,
243                !Roles::uninterruptible_) {
244     return AllocObjectWithAllocator<kInstrumented>(self,
245                                                    klass,
246                                                    num_bytes,
247                                                    GetCurrentAllocator(),
248                                                    pre_fence_visitor);
249   }
250 
251   template <bool kInstrumented = true, typename PreFenceVisitor>
AllocNonMovableObject(Thread * self,ObjPtr<mirror::Class> klass,size_t num_bytes,const PreFenceVisitor & pre_fence_visitor)252   mirror::Object* AllocNonMovableObject(Thread* self,
253                                         ObjPtr<mirror::Class> klass,
254                                         size_t num_bytes,
255                                         const PreFenceVisitor& pre_fence_visitor)
256       REQUIRES_SHARED(Locks::mutator_lock_)
257       REQUIRES(!*gc_complete_lock_,
258                !*pending_task_lock_,
259                !*backtrace_lock_,
260                !process_state_update_lock_,
261                !Roles::uninterruptible_) {
262     mirror::Object* obj = AllocObjectWithAllocator<kInstrumented>(self,
263                                                                   klass,
264                                                                   num_bytes,
265                                                                   GetCurrentNonMovingAllocator(),
266                                                                   pre_fence_visitor);
267     // Java Heap Profiler check and sample allocation.
268     JHPCheckNonTlabSampleAllocation(self, obj, num_bytes);
269     return obj;
270   }
271 
272   template <bool kInstrumented = true, bool kCheckLargeObject = true, typename PreFenceVisitor>
273   ALWAYS_INLINE mirror::Object* AllocObjectWithAllocator(Thread* self,
274                                                          ObjPtr<mirror::Class> klass,
275                                                          size_t byte_count,
276                                                          AllocatorType allocator,
277                                                          const PreFenceVisitor& pre_fence_visitor)
278       REQUIRES_SHARED(Locks::mutator_lock_)
279       REQUIRES(!*gc_complete_lock_,
280                !*pending_task_lock_,
281                !*backtrace_lock_,
282                !process_state_update_lock_,
283                !Roles::uninterruptible_);
284 
GetCurrentAllocator()285   AllocatorType GetCurrentAllocator() const {
286     return current_allocator_;
287   }
288 
GetCurrentNonMovingAllocator()289   AllocatorType GetCurrentNonMovingAllocator() const {
290     return current_non_moving_allocator_;
291   }
292 
GetUpdatedAllocator(AllocatorType old_allocator)293   AllocatorType GetUpdatedAllocator(AllocatorType old_allocator) {
294     return (old_allocator == kAllocatorTypeNonMoving) ?
295         GetCurrentNonMovingAllocator() : GetCurrentAllocator();
296   }
297 
298   // Visit all of the live objects in the heap.
299   template <typename Visitor>
300   ALWAYS_INLINE void VisitObjects(Visitor&& visitor)
301       REQUIRES_SHARED(Locks::mutator_lock_)
302       REQUIRES(!Locks::heap_bitmap_lock_, !*gc_complete_lock_);
303   template <typename Visitor>
304   ALWAYS_INLINE void VisitObjectsPaused(Visitor&& visitor)
305       REQUIRES(Locks::mutator_lock_, !Locks::heap_bitmap_lock_, !*gc_complete_lock_);
306 
307   void VisitReflectiveTargets(ReflectiveValueVisitor* visitor)
308       REQUIRES(Locks::mutator_lock_, !Locks::heap_bitmap_lock_, !*gc_complete_lock_);
309 
310   void CheckPreconditionsForAllocObject(ObjPtr<mirror::Class> c, size_t byte_count)
311       REQUIRES_SHARED(Locks::mutator_lock_);
312 
313   // Inform the garbage collector of a non-malloc allocated native memory that might become
314   // reclaimable in the future as a result of Java garbage collection.
315   void RegisterNativeAllocation(JNIEnv* env, size_t bytes)
316       REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_);
317   void RegisterNativeFree(JNIEnv* env, size_t bytes);
318 
319   // Notify the garbage collector of malloc allocations that might be reclaimable
320   // as a result of Java garbage collection. Each such call represents approximately
321   // kNotifyNativeInterval such allocations.
322   void NotifyNativeAllocations(JNIEnv* env)
323       REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_);
324 
GetNotifyNativeInterval()325   uint32_t GetNotifyNativeInterval() {
326     return kNotifyNativeInterval;
327   }
328 
329   // Change the allocator, updates entrypoints.
330   void ChangeAllocator(AllocatorType allocator)
331       REQUIRES(Locks::mutator_lock_, !Locks::runtime_shutdown_lock_);
332 
333   // Change the collector to be one of the possible options (MS, CMS, SS).
334   void ChangeCollector(CollectorType collector_type)
335       REQUIRES(Locks::mutator_lock_);
336 
337   // The given reference is believed to be to an object in the Java heap, check the soundness of it.
338   // TODO: NO_THREAD_SAFETY_ANALYSIS since we call this everywhere and it is impossible to find a
339   // proper lock ordering for it.
340   void VerifyObjectBody(ObjPtr<mirror::Object> o) NO_THREAD_SAFETY_ANALYSIS;
341 
342   // Consistency check of all live references.
343   void VerifyHeap() REQUIRES(!Locks::heap_bitmap_lock_);
344   // Returns how many failures occured.
345   size_t VerifyHeapReferences(bool verify_referents = true)
346       REQUIRES(Locks::mutator_lock_, !*gc_complete_lock_);
347   bool VerifyMissingCardMarks()
348       REQUIRES(Locks::heap_bitmap_lock_, Locks::mutator_lock_);
349 
350   // A weaker test than IsLiveObject or VerifyObject that doesn't require the heap lock,
351   // and doesn't abort on error, allowing the caller to report more
352   // meaningful diagnostics.
353   bool IsValidObjectAddress(const void* obj) const REQUIRES_SHARED(Locks::mutator_lock_);
354 
355   // Faster alternative to IsHeapAddress since finding if an object is in the large object space is
356   // very slow.
357   bool IsNonDiscontinuousSpaceHeapAddress(const void* addr) const
358       REQUIRES_SHARED(Locks::mutator_lock_);
359 
360   // Returns true if 'obj' is a live heap object, false otherwise (including for invalid addresses).
361   // Requires the heap lock to be held.
362   bool IsLiveObjectLocked(ObjPtr<mirror::Object> obj,
363                           bool search_allocation_stack = true,
364                           bool search_live_stack = true,
365                           bool sorted = false)
366       REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_);
367 
368   // Returns true if there is any chance that the object (obj) will move.
369   bool IsMovableObject(ObjPtr<mirror::Object> obj) const REQUIRES_SHARED(Locks::mutator_lock_);
370 
371   // Enables us to compacting GC until objects are released.
372   void IncrementDisableMovingGC(Thread* self) REQUIRES(!*gc_complete_lock_);
373   void DecrementDisableMovingGC(Thread* self) REQUIRES(!*gc_complete_lock_);
374 
375   // Temporarily disable thread flip for JNI critical calls.
376   void IncrementDisableThreadFlip(Thread* self) REQUIRES(!*thread_flip_lock_);
377   void DecrementDisableThreadFlip(Thread* self) REQUIRES(!*thread_flip_lock_);
378   void ThreadFlipBegin(Thread* self) REQUIRES(!*thread_flip_lock_);
379   void ThreadFlipEnd(Thread* self) REQUIRES(!*thread_flip_lock_);
380 
381   // Clear all of the mark bits, doesn't clear bitmaps which have the same live bits as mark bits.
382   // Mutator lock is required for GetContinuousSpaces.
383   void ClearMarkedObjects()
384       REQUIRES(Locks::heap_bitmap_lock_)
385       REQUIRES_SHARED(Locks::mutator_lock_);
386 
387   // Initiates an explicit garbage collection. Guarantees that a GC started after this call has
388   // completed.
389   void CollectGarbage(bool clear_soft_references, GcCause cause = kGcCauseExplicit)
390       REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_);
391 
392   // Does a concurrent GC, provided the GC numbered requested_gc_num has not already been
393   // completed. Should only be called by the GC daemon thread through runtime.
394   void ConcurrentGC(Thread* self, GcCause cause, bool force_full, uint32_t requested_gc_num)
395       REQUIRES(!Locks::runtime_shutdown_lock_, !*gc_complete_lock_,
396                !*pending_task_lock_, !process_state_update_lock_);
397 
398   // Implements VMDebug.countInstancesOfClass and JDWP VM_InstanceCount.
399   // The boolean decides whether to use IsAssignableFrom or == when comparing classes.
400   void CountInstances(const std::vector<Handle<mirror::Class>>& classes,
401                       bool use_is_assignable_from,
402                       uint64_t* counts)
403       REQUIRES(!Locks::heap_bitmap_lock_, !*gc_complete_lock_)
404       REQUIRES_SHARED(Locks::mutator_lock_);
405 
406   // Removes the growth limit on the alloc space so it may grow to its maximum capacity. Used to
407   // implement dalvik.system.VMRuntime.clearGrowthLimit.
408   void ClearGrowthLimit();
409 
410   // Make the current growth limit the new maximum capacity, unmaps pages at the end of spaces
411   // which will never be used. Used to implement dalvik.system.VMRuntime.clampGrowthLimit.
412   void ClampGrowthLimit() REQUIRES(!Locks::heap_bitmap_lock_);
413 
414   // Target ideal heap utilization ratio, implements
415   // dalvik.system.VMRuntime.getTargetHeapUtilization.
GetTargetHeapUtilization()416   double GetTargetHeapUtilization() const {
417     return target_utilization_;
418   }
419 
420   // Data structure memory usage tracking.
421   void RegisterGCAllocation(size_t bytes);
422   void RegisterGCDeAllocation(size_t bytes);
423 
424   // Set the heap's private space pointers to be the same as the space based on it's type. Public
425   // due to usage by tests.
426   void SetSpaceAsDefault(space::ContinuousSpace* continuous_space)
427       REQUIRES(!Locks::heap_bitmap_lock_);
428   void AddSpace(space::Space* space)
429       REQUIRES(!Locks::heap_bitmap_lock_)
430       REQUIRES(Locks::mutator_lock_);
431   void RemoveSpace(space::Space* space)
432     REQUIRES(!Locks::heap_bitmap_lock_)
433     REQUIRES(Locks::mutator_lock_);
434 
GetPreGcWeightedAllocatedBytes()435   double GetPreGcWeightedAllocatedBytes() const {
436     return pre_gc_weighted_allocated_bytes_;
437   }
438 
GetPostGcWeightedAllocatedBytes()439   double GetPostGcWeightedAllocatedBytes() const {
440     return post_gc_weighted_allocated_bytes_;
441   }
442 
443   void CalculatePreGcWeightedAllocatedBytes();
444   void CalculatePostGcWeightedAllocatedBytes();
445   uint64_t GetTotalGcCpuTime();
446 
GetProcessCpuStartTime()447   uint64_t GetProcessCpuStartTime() const {
448     return process_cpu_start_time_ns_;
449   }
450 
GetPostGCLastProcessCpuTime()451   uint64_t GetPostGCLastProcessCpuTime() const {
452     return post_gc_last_process_cpu_time_ns_;
453   }
454 
455   // Set target ideal heap utilization ratio, implements
456   // dalvik.system.VMRuntime.setTargetHeapUtilization.
457   void SetTargetHeapUtilization(float target);
458 
459   // For the alloc space, sets the maximum number of bytes that the heap is allowed to allocate
460   // from the system. Doesn't allow the space to exceed its growth limit.
461   void SetIdealFootprint(size_t max_allowed_footprint);
462 
463   // Blocks the caller until the garbage collector becomes idle and returns the type of GC we
464   // waited for. Only waits for running collections, ignoring a requested but unstarted GC. Only
465   // heuristic, since a new GC may have started by the time we return.
466   collector::GcType WaitForGcToComplete(GcCause cause, Thread* self) REQUIRES(!*gc_complete_lock_);
467 
468   // Update the heap's process state to a new value, may cause compaction to occur.
469   void UpdateProcessState(ProcessState old_process_state, ProcessState new_process_state)
470       REQUIRES(!*pending_task_lock_, !*gc_complete_lock_, !process_state_update_lock_);
471 
HaveContinuousSpaces()472   bool HaveContinuousSpaces() const NO_THREAD_SAFETY_ANALYSIS {
473     // No lock since vector empty is thread safe.
474     return !continuous_spaces_.empty();
475   }
476 
GetContinuousSpaces()477   const std::vector<space::ContinuousSpace*>& GetContinuousSpaces() const
478       REQUIRES_SHARED(Locks::mutator_lock_) {
479     return continuous_spaces_;
480   }
481 
GetDiscontinuousSpaces()482   const std::vector<space::DiscontinuousSpace*>& GetDiscontinuousSpaces() const {
483     return discontinuous_spaces_;
484   }
485 
GetCurrentGcIteration()486   const collector::Iteration* GetCurrentGcIteration() const {
487     return &current_gc_iteration_;
488   }
GetCurrentGcIteration()489   collector::Iteration* GetCurrentGcIteration() {
490     return &current_gc_iteration_;
491   }
492 
493   // Enable verification of object references when the runtime is sufficiently initialized.
EnableObjectValidation()494   void EnableObjectValidation() {
495     verify_object_mode_ = kVerifyObjectSupport;
496     if (verify_object_mode_ > kVerifyObjectModeDisabled) {
497       VerifyHeap();
498     }
499   }
500 
501   // Disable object reference verification for image writing.
DisableObjectValidation()502   void DisableObjectValidation() {
503     verify_object_mode_ = kVerifyObjectModeDisabled;
504   }
505 
506   // Other checks may be performed if we know the heap should be in a healthy state.
IsObjectValidationEnabled()507   bool IsObjectValidationEnabled() const {
508     return verify_object_mode_ > kVerifyObjectModeDisabled;
509   }
510 
511   // Returns true if low memory mode is enabled.
IsLowMemoryMode()512   bool IsLowMemoryMode() const {
513     return low_memory_mode_;
514   }
515 
516   // Returns the heap growth multiplier, this affects how much we grow the heap after a GC.
517   // Scales heap growth, min free, and max free.
518   double HeapGrowthMultiplier() const;
519 
520   // Freed bytes can be negative in cases where we copy objects from a compacted space to a
521   // free-list backed space.
522   void RecordFree(uint64_t freed_objects, int64_t freed_bytes);
523 
524   // Record the bytes freed by thread-local buffer revoke.
525   void RecordFreeRevoke();
526 
GetCardTable()527   accounting::CardTable* GetCardTable() const {
528     return card_table_.get();
529   }
530 
GetReadBarrierTable()531   accounting::ReadBarrierTable* GetReadBarrierTable() const {
532     return rb_table_.get();
533   }
534 
535   void AddFinalizerReference(Thread* self, ObjPtr<mirror::Object>* object);
536 
537   // Returns the number of bytes currently allocated.
538   // The result should be treated as an approximation, if it is being concurrently updated.
GetBytesAllocated()539   size_t GetBytesAllocated() const {
540     return num_bytes_allocated_.load(std::memory_order_relaxed);
541   }
542 
GetUseGenerationalCC()543   bool GetUseGenerationalCC() const {
544     return use_generational_cc_;
545   }
546 
547   // Returns the number of objects currently allocated.
548   size_t GetObjectsAllocated() const
549       REQUIRES(!Locks::heap_bitmap_lock_);
550 
551   // Returns the total number of objects allocated since the heap was created.
552   uint64_t GetObjectsAllocatedEver() const;
553 
554   // Returns the total number of bytes allocated since the heap was created.
555   uint64_t GetBytesAllocatedEver() const;
556 
557   // Returns the total number of objects freed since the heap was created.
558   // With default memory order, this should be viewed only as a hint.
559   uint64_t GetObjectsFreedEver(std::memory_order mo = std::memory_order_relaxed) const {
560     return total_objects_freed_ever_.load(mo);
561   }
562 
563   // Returns the total number of bytes freed since the heap was created.
564   // With default memory order, this should be viewed only as a hint.
565   uint64_t GetBytesFreedEver(std::memory_order mo = std::memory_order_relaxed) const {
566     return total_bytes_freed_ever_.load(mo);
567   }
568 
GetRegionSpace()569   space::RegionSpace* GetRegionSpace() const {
570     return region_space_;
571   }
572 
573   // Implements java.lang.Runtime.maxMemory, returning the maximum amount of memory a program can
574   // consume. For a regular VM this would relate to the -Xmx option and would return -1 if no Xmx
575   // were specified. Android apps start with a growth limit (small heap size) which is
576   // cleared/extended for large apps.
GetMaxMemory()577   size_t GetMaxMemory() const {
578     // There are some race conditions in the allocation code that can cause bytes allocated to
579     // become larger than growth_limit_ in rare cases.
580     return std::max(GetBytesAllocated(), growth_limit_);
581   }
582 
583   // Implements java.lang.Runtime.totalMemory, returning approximate amount of memory currently
584   // consumed by an application.
585   size_t GetTotalMemory() const;
586 
587   // Returns approximately how much free memory we have until the next GC happens.
GetFreeMemoryUntilGC()588   size_t GetFreeMemoryUntilGC() const {
589     return UnsignedDifference(target_footprint_.load(std::memory_order_relaxed),
590                               GetBytesAllocated());
591   }
592 
593   // Returns approximately how much free memory we have until the next OOME happens.
GetFreeMemoryUntilOOME()594   size_t GetFreeMemoryUntilOOME() const {
595     return UnsignedDifference(growth_limit_, GetBytesAllocated());
596   }
597 
598   // Returns how much free memory we have until we need to grow the heap to perform an allocation.
599   // Similar to GetFreeMemoryUntilGC. Implements java.lang.Runtime.freeMemory.
GetFreeMemory()600   size_t GetFreeMemory() const {
601     return UnsignedDifference(GetTotalMemory(),
602                               num_bytes_allocated_.load(std::memory_order_relaxed));
603   }
604 
605   // Get the space that corresponds to an object's address. Current implementation searches all
606   // spaces in turn. If fail_ok is false then failing to find a space will cause an abort.
607   // TODO: consider using faster data structure like binary tree.
608   space::ContinuousSpace* FindContinuousSpaceFromObject(ObjPtr<mirror::Object>, bool fail_ok) const
609       REQUIRES_SHARED(Locks::mutator_lock_);
610 
611   space::ContinuousSpace* FindContinuousSpaceFromAddress(const mirror::Object* addr) const
612       REQUIRES_SHARED(Locks::mutator_lock_);
613 
614   space::DiscontinuousSpace* FindDiscontinuousSpaceFromObject(ObjPtr<mirror::Object>,
615                                                               bool fail_ok) const
616       REQUIRES_SHARED(Locks::mutator_lock_);
617 
618   space::Space* FindSpaceFromObject(ObjPtr<mirror::Object> obj, bool fail_ok) const
619       REQUIRES_SHARED(Locks::mutator_lock_);
620 
621   space::Space* FindSpaceFromAddress(const void* ptr) const
622       REQUIRES_SHARED(Locks::mutator_lock_);
623 
624   std::string DumpSpaceNameFromAddress(const void* addr) const
625       REQUIRES_SHARED(Locks::mutator_lock_);
626 
627   void DumpForSigQuit(std::ostream& os) REQUIRES(!*gc_complete_lock_);
628 
629   // Do a pending collector transition.
630   void DoPendingCollectorTransition()
631       REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_);
632 
633   // Deflate monitors, ... and trim the spaces.
634   void Trim(Thread* self) REQUIRES(!*gc_complete_lock_);
635 
636   void RevokeThreadLocalBuffers(Thread* thread);
637   void RevokeRosAllocThreadLocalBuffers(Thread* thread);
638   void RevokeAllThreadLocalBuffers();
639   void AssertThreadLocalBuffersAreRevoked(Thread* thread);
640   void AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked();
641   void RosAllocVerification(TimingLogger* timings, const char* name)
642       REQUIRES(Locks::mutator_lock_);
643 
GetLiveBitmap()644   accounting::HeapBitmap* GetLiveBitmap() REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
645     return live_bitmap_.get();
646   }
647 
GetMarkBitmap()648   accounting::HeapBitmap* GetMarkBitmap() REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
649     return mark_bitmap_.get();
650   }
651 
GetLiveStack()652   accounting::ObjectStack* GetLiveStack() REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
653     return live_stack_.get();
654   }
655 
656   void PreZygoteFork() NO_THREAD_SAFETY_ANALYSIS;
657 
658   // Mark and empty stack.
659   void FlushAllocStack()
660       REQUIRES_SHARED(Locks::mutator_lock_)
661       REQUIRES(Locks::heap_bitmap_lock_);
662 
663   // Revoke all the thread-local allocation stacks.
664   void RevokeAllThreadLocalAllocationStacks(Thread* self)
665       REQUIRES(Locks::mutator_lock_, !Locks::runtime_shutdown_lock_, !Locks::thread_list_lock_);
666 
667   // Mark all the objects in the allocation stack in the specified bitmap.
668   // TODO: Refactor?
669   void MarkAllocStack(accounting::SpaceBitmap<kObjectAlignment>* bitmap1,
670                       accounting::SpaceBitmap<kObjectAlignment>* bitmap2,
671                       accounting::SpaceBitmap<kLargeObjectAlignment>* large_objects,
672                       accounting::ObjectStack* stack)
673       REQUIRES_SHARED(Locks::mutator_lock_)
674       REQUIRES(Locks::heap_bitmap_lock_);
675 
676   // Mark the specified allocation stack as live.
677   void MarkAllocStackAsLive(accounting::ObjectStack* stack)
678       REQUIRES_SHARED(Locks::mutator_lock_)
679       REQUIRES(Locks::heap_bitmap_lock_);
680 
681   // Unbind any bound bitmaps.
682   void UnBindBitmaps()
683       REQUIRES(Locks::heap_bitmap_lock_)
684       REQUIRES_SHARED(Locks::mutator_lock_);
685 
686   // Returns the boot image spaces. There may be multiple boot image spaces.
GetBootImageSpaces()687   const std::vector<space::ImageSpace*>& GetBootImageSpaces() const {
688     return boot_image_spaces_;
689   }
690 
691   bool ObjectIsInBootImageSpace(ObjPtr<mirror::Object> obj) const
692       REQUIRES_SHARED(Locks::mutator_lock_);
693 
694   bool IsInBootImageOatFile(const void* p) const
695       REQUIRES_SHARED(Locks::mutator_lock_);
696 
697   // Get the start address of the boot images if any; otherwise returns 0.
GetBootImagesStartAddress()698   uint32_t GetBootImagesStartAddress() const {
699     return boot_images_start_address_;
700   }
701 
702   // Get the size of all boot images, including the heap and oat areas.
GetBootImagesSize()703   uint32_t GetBootImagesSize() const {
704     return boot_images_size_;
705   }
706 
707   // Check if a pointer points to a boot image.
IsBootImageAddress(const void * p)708   bool IsBootImageAddress(const void* p) const {
709     return reinterpret_cast<uintptr_t>(p) - boot_images_start_address_ < boot_images_size_;
710   }
711 
GetDlMallocSpace()712   space::DlMallocSpace* GetDlMallocSpace() const {
713     return dlmalloc_space_;
714   }
715 
GetRosAllocSpace()716   space::RosAllocSpace* GetRosAllocSpace() const {
717     return rosalloc_space_;
718   }
719 
720   // Return the corresponding rosalloc space.
721   space::RosAllocSpace* GetRosAllocSpace(gc::allocator::RosAlloc* rosalloc) const
722       REQUIRES_SHARED(Locks::mutator_lock_);
723 
GetNonMovingSpace()724   space::MallocSpace* GetNonMovingSpace() const {
725     return non_moving_space_;
726   }
727 
GetLargeObjectsSpace()728   space::LargeObjectSpace* GetLargeObjectsSpace() const {
729     return large_object_space_;
730   }
731 
732   // Returns the free list space that may contain movable objects (the
733   // one that's not the non-moving space), either rosalloc_space_ or
734   // dlmalloc_space_.
GetPrimaryFreeListSpace()735   space::MallocSpace* GetPrimaryFreeListSpace() {
736     if (kUseRosAlloc) {
737       DCHECK(rosalloc_space_ != nullptr);
738       // reinterpret_cast is necessary as the space class hierarchy
739       // isn't known (#included) yet here.
740       return reinterpret_cast<space::MallocSpace*>(rosalloc_space_);
741     } else {
742       DCHECK(dlmalloc_space_ != nullptr);
743       return reinterpret_cast<space::MallocSpace*>(dlmalloc_space_);
744     }
745   }
746 
747   void DumpSpaces(std::ostream& stream) const REQUIRES_SHARED(Locks::mutator_lock_);
748   std::string DumpSpaces() const REQUIRES_SHARED(Locks::mutator_lock_);
749 
750   // GC performance measuring
751   void DumpGcPerformanceInfo(std::ostream& os)
752       REQUIRES(!*gc_complete_lock_);
753   void ResetGcPerformanceInfo() REQUIRES(!*gc_complete_lock_);
754 
755   // Thread pool.
756   void CreateThreadPool();
757   void DeleteThreadPool();
GetThreadPool()758   ThreadPool* GetThreadPool() {
759     return thread_pool_.get();
760   }
GetParallelGCThreadCount()761   size_t GetParallelGCThreadCount() const {
762     return parallel_gc_threads_;
763   }
GetConcGCThreadCount()764   size_t GetConcGCThreadCount() const {
765     return conc_gc_threads_;
766   }
767   accounting::ModUnionTable* FindModUnionTableFromSpace(space::Space* space);
768   void AddModUnionTable(accounting::ModUnionTable* mod_union_table);
769 
770   accounting::RememberedSet* FindRememberedSetFromSpace(space::Space* space);
771   void AddRememberedSet(accounting::RememberedSet* remembered_set);
772   // Also deletes the remebered set.
773   void RemoveRememberedSet(space::Space* space);
774 
775   bool IsCompilingBoot() const;
HasBootImageSpace()776   bool HasBootImageSpace() const {
777     return !boot_image_spaces_.empty();
778   }
779 
GetReferenceProcessor()780   ReferenceProcessor* GetReferenceProcessor() {
781     return reference_processor_.get();
782   }
GetTaskProcessor()783   TaskProcessor* GetTaskProcessor() {
784     return task_processor_.get();
785   }
786 
HasZygoteSpace()787   bool HasZygoteSpace() const {
788     return zygote_space_ != nullptr;
789   }
790 
791   // Returns the active concurrent copying collector.
ConcurrentCopyingCollector()792   collector::ConcurrentCopying* ConcurrentCopyingCollector() {
793     collector::ConcurrentCopying* active_collector =
794             active_concurrent_copying_collector_.load(std::memory_order_relaxed);
795     if (use_generational_cc_) {
796       DCHECK((active_collector == concurrent_copying_collector_) ||
797              (active_collector == young_concurrent_copying_collector_))
798               << "active_concurrent_copying_collector: " << active_collector
799               << " young_concurrent_copying_collector: " << young_concurrent_copying_collector_
800               << " concurrent_copying_collector: " << concurrent_copying_collector_;
801     } else {
802       DCHECK_EQ(active_collector, concurrent_copying_collector_);
803     }
804     return active_collector;
805   }
806 
CurrentCollectorType()807   CollectorType CurrentCollectorType() {
808     return collector_type_;
809   }
810 
IsGcConcurrentAndMoving()811   bool IsGcConcurrentAndMoving() const {
812     if (IsGcConcurrent() && IsMovingGc(collector_type_)) {
813       // Assume no transition when a concurrent moving collector is used.
814       DCHECK_EQ(collector_type_, foreground_collector_type_);
815       return true;
816     }
817     return false;
818   }
819 
IsMovingGCDisabled(Thread * self)820   bool IsMovingGCDisabled(Thread* self) REQUIRES(!*gc_complete_lock_) {
821     MutexLock mu(self, *gc_complete_lock_);
822     return disable_moving_gc_count_ > 0;
823   }
824 
825   // Request an asynchronous trim.
826   void RequestTrim(Thread* self) REQUIRES(!*pending_task_lock_);
827 
828   // Retrieve the current GC number, i.e. the number n such that we completed n GCs so far.
829   // Provides acquire ordering, so that if we read this first, and then check whether a GC is
830   // required, we know that the GC number read actually preceded the test.
GetCurrentGcNum()831   uint32_t GetCurrentGcNum() {
832     return gcs_completed_.load(std::memory_order_acquire);
833   }
834 
835   // Request asynchronous GC. Observed_gc_num is the value of GetCurrentGcNum() when we started to
836   // evaluate the GC triggering condition. If a GC has been completed since then, we consider our
837   // job done. If we return true, then we ensured that gcs_completed_ will eventually be
838   // incremented beyond observed_gc_num. We return false only in corner cases in which we cannot
839   // ensure that.
840   bool RequestConcurrentGC(Thread* self, GcCause cause, bool force_full, uint32_t observed_gc_num)
841       REQUIRES(!*pending_task_lock_);
842 
843   // Whether or not we may use a garbage collector, used so that we only create collectors we need.
844   bool MayUseCollector(CollectorType type) const;
845 
846   // Used by tests to reduce timinig-dependent flakiness in OOME behavior.
SetMinIntervalHomogeneousSpaceCompactionByOom(uint64_t interval)847   void SetMinIntervalHomogeneousSpaceCompactionByOom(uint64_t interval) {
848     min_interval_homogeneous_space_compaction_by_oom_ = interval;
849   }
850 
851   // Helpers for android.os.Debug.getRuntimeStat().
852   uint64_t GetGcCount() const;
853   uint64_t GetGcTime() const;
854   uint64_t GetBlockingGcCount() const;
855   uint64_t GetBlockingGcTime() const;
856   void DumpGcCountRateHistogram(std::ostream& os) const REQUIRES(!*gc_complete_lock_);
857   void DumpBlockingGcCountRateHistogram(std::ostream& os) const REQUIRES(!*gc_complete_lock_);
GetTotalTimeWaitingForGC()858   uint64_t GetTotalTimeWaitingForGC() const {
859     return total_wait_time_;
860   }
861 
862   // Perfetto Art Heap Profiler Support.
GetHeapSampler()863   HeapSampler& GetHeapSampler() {
864     return heap_sampler_;
865   }
866 
867   void InitPerfettoJavaHeapProf();
868   int CheckPerfettoJHPEnabled();
869   // In NonTlab case: Check whether we should report a sample allocation and if so report it.
870   // Also update state (bytes_until_sample).
871   // By calling JHPCheckNonTlabSampleAllocation from different functions for Large allocations and
872   // non-moving allocations we are able to use the stack to identify these allocations separately.
873   void JHPCheckNonTlabSampleAllocation(Thread* self,
874                                        mirror::Object* ret,
875                                        size_t alloc_size);
876   // In Tlab case: Calculate the next tlab size (location of next sample point) and whether
877   // a sample should be taken.
878   size_t JHPCalculateNextTlabSize(Thread* self,
879                                   size_t jhp_def_tlab_size,
880                                   size_t alloc_size,
881                                   bool* take_sample,
882                                   size_t* bytes_until_sample);
883   // Reduce the number of bytes to the next sample position by this adjustment.
884   void AdjustSampleOffset(size_t adjustment);
885 
886   // Allocation tracking support
887   // Callers to this function use double-checked locking to ensure safety on allocation_records_
IsAllocTrackingEnabled()888   bool IsAllocTrackingEnabled() const {
889     return alloc_tracking_enabled_.load(std::memory_order_relaxed);
890   }
891 
SetAllocTrackingEnabled(bool enabled)892   void SetAllocTrackingEnabled(bool enabled) REQUIRES(Locks::alloc_tracker_lock_) {
893     alloc_tracking_enabled_.store(enabled, std::memory_order_relaxed);
894   }
895 
896   // Return the current stack depth of allocation records.
GetAllocTrackerStackDepth()897   size_t GetAllocTrackerStackDepth() const {
898     return alloc_record_depth_;
899   }
900 
901   // Return the current stack depth of allocation records.
SetAllocTrackerStackDepth(size_t alloc_record_depth)902   void SetAllocTrackerStackDepth(size_t alloc_record_depth) {
903     alloc_record_depth_ = alloc_record_depth;
904   }
905 
GetAllocationRecords()906   AllocRecordObjectMap* GetAllocationRecords() const REQUIRES(Locks::alloc_tracker_lock_) {
907     return allocation_records_.get();
908   }
909 
910   void SetAllocationRecords(AllocRecordObjectMap* records)
911       REQUIRES(Locks::alloc_tracker_lock_);
912 
913   void VisitAllocationRecords(RootVisitor* visitor) const
914       REQUIRES_SHARED(Locks::mutator_lock_)
915       REQUIRES(!Locks::alloc_tracker_lock_);
916 
917   void SweepAllocationRecords(IsMarkedVisitor* visitor) const
918       REQUIRES_SHARED(Locks::mutator_lock_)
919       REQUIRES(!Locks::alloc_tracker_lock_);
920 
921   void DisallowNewAllocationRecords() const
922       REQUIRES_SHARED(Locks::mutator_lock_)
923       REQUIRES(!Locks::alloc_tracker_lock_);
924 
925   void AllowNewAllocationRecords() const
926       REQUIRES_SHARED(Locks::mutator_lock_)
927       REQUIRES(!Locks::alloc_tracker_lock_);
928 
929   void BroadcastForNewAllocationRecords() const
930       REQUIRES(!Locks::alloc_tracker_lock_);
931 
932   void DisableGCForShutdown() REQUIRES(!*gc_complete_lock_);
933 
934   // Create a new alloc space and compact default alloc space to it.
935   HomogeneousSpaceCompactResult PerformHomogeneousSpaceCompact()
936       REQUIRES(!*gc_complete_lock_, !process_state_update_lock_);
937   bool SupportHomogeneousSpaceCompactAndCollectorTransitions() const;
938 
939   // Install an allocation listener.
940   void SetAllocationListener(AllocationListener* l);
941   // Remove an allocation listener. Note: the listener must not be deleted, as for performance
942   // reasons, we assume it stays valid when we read it (so that we don't require a lock).
943   void RemoveAllocationListener();
944 
945   // Install a gc pause listener.
946   void SetGcPauseListener(GcPauseListener* l);
947   // Get the currently installed gc pause listener, or null.
GetGcPauseListener()948   GcPauseListener* GetGcPauseListener() {
949     return gc_pause_listener_.load(std::memory_order_acquire);
950   }
951   // Remove a gc pause listener. Note: the listener must not be deleted, as for performance
952   // reasons, we assume it stays valid when we read it (so that we don't require a lock).
953   void RemoveGcPauseListener();
954 
955   const Verification* GetVerification() const;
956 
957   void PostForkChildAction(Thread* self);
958 
959   void TraceHeapSize(size_t heap_size);
960 
961   bool AddHeapTask(gc::HeapTask* task);
962 
963  private:
964   class ConcurrentGCTask;
965   class CollectorTransitionTask;
966   class HeapTrimTask;
967   class TriggerPostForkCCGcTask;
968 
969   // Compact source space to target space. Returns the collector used.
970   collector::GarbageCollector* Compact(space::ContinuousMemMapAllocSpace* target_space,
971                                        space::ContinuousMemMapAllocSpace* source_space,
972                                        GcCause gc_cause)
973       REQUIRES(Locks::mutator_lock_);
974 
975   void LogGC(GcCause gc_cause, collector::GarbageCollector* collector);
976   void StartGC(Thread* self, GcCause cause, CollectorType collector_type)
977       REQUIRES(!*gc_complete_lock_);
978   void FinishGC(Thread* self, collector::GcType gc_type) REQUIRES(!*gc_complete_lock_);
979 
980   double CalculateGcWeightedAllocatedBytes(uint64_t gc_last_process_cpu_time_ns,
981                                            uint64_t current_process_cpu_time) const;
982 
983   // Create a mem map with a preferred base address.
984   static MemMap MapAnonymousPreferredAddress(const char* name,
985                                              uint8_t* request_begin,
986                                              size_t capacity,
987                                              std::string* out_error_str);
988 
SupportHSpaceCompaction()989   bool SupportHSpaceCompaction() const {
990     // Returns true if we can do hspace compaction
991     return main_space_backup_ != nullptr;
992   }
993 
994   // Size_t saturating arithmetic
UnsignedDifference(size_t x,size_t y)995   static ALWAYS_INLINE size_t UnsignedDifference(size_t x, size_t y) {
996     return x > y ? x - y : 0;
997   }
UnsignedSum(size_t x,size_t y)998   static ALWAYS_INLINE size_t UnsignedSum(size_t x, size_t y) {
999     return x + y >= x ? x + y : std::numeric_limits<size_t>::max();
1000   }
1001 
AllocatorHasAllocationStack(AllocatorType allocator_type)1002   static ALWAYS_INLINE bool AllocatorHasAllocationStack(AllocatorType allocator_type) {
1003     return
1004         allocator_type != kAllocatorTypeRegionTLAB &&
1005         allocator_type != kAllocatorTypeBumpPointer &&
1006         allocator_type != kAllocatorTypeTLAB &&
1007         allocator_type != kAllocatorTypeRegion;
1008   }
AllocatorMayHaveConcurrentGC(AllocatorType allocator_type)1009   static ALWAYS_INLINE bool AllocatorMayHaveConcurrentGC(AllocatorType allocator_type) {
1010     if (kUseReadBarrier) {
1011       // Read barrier may have the TLAB allocator but is always concurrent. TODO: clean this up.
1012       return true;
1013     }
1014     return
1015         allocator_type != kAllocatorTypeTLAB &&
1016         allocator_type != kAllocatorTypeBumpPointer;
1017   }
IsMovingGc(CollectorType collector_type)1018   static bool IsMovingGc(CollectorType collector_type) {
1019     return
1020         collector_type == kCollectorTypeCC ||
1021         collector_type == kCollectorTypeSS ||
1022         collector_type == kCollectorTypeCCBackground ||
1023         collector_type == kCollectorTypeHomogeneousSpaceCompact;
1024   }
1025   bool ShouldAllocLargeObject(ObjPtr<mirror::Class> c, size_t byte_count) const
1026       REQUIRES_SHARED(Locks::mutator_lock_);
1027 
1028   // Checks whether we should garbage collect:
1029   ALWAYS_INLINE bool ShouldConcurrentGCForJava(size_t new_num_bytes_allocated);
1030   float NativeMemoryOverTarget(size_t current_native_bytes, bool is_gc_concurrent);
1031   void CheckGCForNative(Thread* self)
1032       REQUIRES(!*pending_task_lock_, !*gc_complete_lock_, !process_state_update_lock_);
1033 
GetMarkStack()1034   accounting::ObjectStack* GetMarkStack() {
1035     return mark_stack_.get();
1036   }
1037 
1038   // We don't force this to be inlined since it is a slow path.
1039   template <bool kInstrumented, typename PreFenceVisitor>
1040   mirror::Object* AllocLargeObject(Thread* self,
1041                                    ObjPtr<mirror::Class>* klass,
1042                                    size_t byte_count,
1043                                    const PreFenceVisitor& pre_fence_visitor)
1044       REQUIRES_SHARED(Locks::mutator_lock_)
1045       REQUIRES(!*gc_complete_lock_, !*pending_task_lock_,
1046                !*backtrace_lock_, !process_state_update_lock_);
1047 
1048   // Handles Allocate()'s slow allocation path with GC involved after an initial allocation
1049   // attempt failed.
1050   // Called with thread suspension disallowed, but re-enables it, and may suspend, internally.
1051   // Returns null if instrumentation or the allocator changed.
1052   mirror::Object* AllocateInternalWithGc(Thread* self,
1053                                          AllocatorType allocator,
1054                                          bool instrumented,
1055                                          size_t num_bytes,
1056                                          size_t* bytes_allocated,
1057                                          size_t* usable_size,
1058                                          size_t* bytes_tl_bulk_allocated,
1059                                          ObjPtr<mirror::Class>* klass)
1060       REQUIRES(!Locks::thread_suspend_count_lock_, !*gc_complete_lock_, !*pending_task_lock_)
1061       REQUIRES(Roles::uninterruptible_)
1062       REQUIRES_SHARED(Locks::mutator_lock_);
1063 
1064   // Allocate into a specific space.
1065   mirror::Object* AllocateInto(Thread* self,
1066                                space::AllocSpace* space,
1067                                ObjPtr<mirror::Class> c,
1068                                size_t bytes)
1069       REQUIRES_SHARED(Locks::mutator_lock_);
1070 
1071   // Need to do this with mutators paused so that somebody doesn't accidentally allocate into the
1072   // wrong space.
1073   void SwapSemiSpaces() REQUIRES(Locks::mutator_lock_);
1074 
1075   // Try to allocate a number of bytes, this function never does any GCs. Needs to be inlined so
1076   // that the switch statement is constant optimized in the entrypoints.
1077   template <const bool kInstrumented, const bool kGrow>
1078   ALWAYS_INLINE mirror::Object* TryToAllocate(Thread* self,
1079                                               AllocatorType allocator_type,
1080                                               size_t alloc_size,
1081                                               size_t* bytes_allocated,
1082                                               size_t* usable_size,
1083                                               size_t* bytes_tl_bulk_allocated)
1084       REQUIRES_SHARED(Locks::mutator_lock_);
1085 
1086   mirror::Object* AllocWithNewTLAB(Thread* self,
1087                                    AllocatorType allocator_type,
1088                                    size_t alloc_size,
1089                                    bool grow,
1090                                    size_t* bytes_allocated,
1091                                    size_t* usable_size,
1092                                    size_t* bytes_tl_bulk_allocated)
1093       REQUIRES_SHARED(Locks::mutator_lock_);
1094 
1095   void ThrowOutOfMemoryError(Thread* self, size_t byte_count, AllocatorType allocator_type)
1096       REQUIRES_SHARED(Locks::mutator_lock_);
1097 
1098   // Are we out of memory, and thus should force a GC or fail?
1099   // For concurrent collectors, out of memory is defined by growth_limit_.
1100   // For nonconcurrent collectors it is defined by target_footprint_ unless grow is
1101   // set. If grow is set, the limit is growth_limit_ and we adjust target_footprint_
1102   // to accomodate the allocation.
1103   ALWAYS_INLINE bool IsOutOfMemoryOnAllocation(AllocatorType allocator_type,
1104                                                size_t alloc_size,
1105                                                bool grow);
1106 
1107   // Run the finalizers. If timeout is non zero, then we use the VMRuntime version.
1108   void RunFinalization(JNIEnv* env, uint64_t timeout);
1109 
1110   // Blocks the caller until the garbage collector becomes idle and returns the type of GC we
1111   // waited for.
1112   collector::GcType WaitForGcToCompleteLocked(GcCause cause, Thread* self)
1113       REQUIRES(gc_complete_lock_);
1114 
1115   void RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time)
1116       REQUIRES(!*pending_task_lock_);
1117 
1118   void RequestConcurrentGCAndSaveObject(Thread* self,
1119                                         bool force_full,
1120                                         uint32_t observed_gc_num,
1121                                         ObjPtr<mirror::Object>* obj)
1122       REQUIRES_SHARED(Locks::mutator_lock_)
1123       REQUIRES(!*pending_task_lock_);
1124 
1125   static constexpr uint32_t GC_NUM_ANY = std::numeric_limits<uint32_t>::max();
1126 
1127   // Sometimes CollectGarbageInternal decides to run a different Gc than you requested. Returns
1128   // which type of Gc was actually run.
1129   // We pass in the intended GC sequence number to ensure that multiple approximately concurrent
1130   // requests result in a single GC; clearly redundant request will be pruned.  A requested_gc_num
1131   // of GC_NUM_ANY indicates that we should not prune redundant requests.  (In the unlikely case
1132   // that gcs_completed_ gets this big, we just accept a potential extra GC or two.)
1133   collector::GcType CollectGarbageInternal(collector::GcType gc_plan,
1134                                            GcCause gc_cause,
1135                                            bool clear_soft_references,
1136                                            uint32_t requested_gc_num)
1137       REQUIRES(!*gc_complete_lock_, !Locks::heap_bitmap_lock_, !Locks::thread_suspend_count_lock_,
1138                !*pending_task_lock_, !process_state_update_lock_);
1139 
1140   void PreGcVerification(collector::GarbageCollector* gc)
1141       REQUIRES(!Locks::mutator_lock_, !*gc_complete_lock_);
1142   void PreGcVerificationPaused(collector::GarbageCollector* gc)
1143       REQUIRES(Locks::mutator_lock_, !*gc_complete_lock_);
1144   void PrePauseRosAllocVerification(collector::GarbageCollector* gc)
1145       REQUIRES(Locks::mutator_lock_);
1146   void PreSweepingGcVerification(collector::GarbageCollector* gc)
1147       REQUIRES(Locks::mutator_lock_, !Locks::heap_bitmap_lock_, !*gc_complete_lock_);
1148   void PostGcVerification(collector::GarbageCollector* gc)
1149       REQUIRES(!Locks::mutator_lock_, !*gc_complete_lock_);
1150   void PostGcVerificationPaused(collector::GarbageCollector* gc)
1151       REQUIRES(Locks::mutator_lock_, !*gc_complete_lock_);
1152 
1153   // Find a collector based on GC type.
1154   collector::GarbageCollector* FindCollectorByGcType(collector::GcType gc_type);
1155 
1156   // Create the main free list malloc space, either a RosAlloc space or DlMalloc space.
1157   void CreateMainMallocSpace(MemMap&& mem_map,
1158                              size_t initial_size,
1159                              size_t growth_limit,
1160                              size_t capacity);
1161 
1162   // Create a malloc space based on a mem map. Does not set the space as default.
1163   space::MallocSpace* CreateMallocSpaceFromMemMap(MemMap&& mem_map,
1164                                                   size_t initial_size,
1165                                                   size_t growth_limit,
1166                                                   size_t capacity,
1167                                                   const char* name,
1168                                                   bool can_move_objects);
1169 
1170   // Given the current contents of the alloc space, increase the allowed heap footprint to match
1171   // the target utilization ratio.  This should only be called immediately after a full garbage
1172   // collection. bytes_allocated_before_gc is used to measure bytes / second for the period which
1173   // the GC was run.
1174   void GrowForUtilization(collector::GarbageCollector* collector_ran,
1175                           size_t bytes_allocated_before_gc = 0)
1176       REQUIRES(!process_state_update_lock_);
1177 
1178   size_t GetPercentFree();
1179 
1180   // Swap the allocation stack with the live stack.
1181   void SwapStacks() REQUIRES_SHARED(Locks::mutator_lock_);
1182 
1183   // Clear cards and update the mod union table. When process_alloc_space_cards is true,
1184   // if clear_alloc_space_cards is true, then we clear cards instead of ageing them. We do
1185   // not process the alloc space if process_alloc_space_cards is false.
1186   void ProcessCards(TimingLogger* timings,
1187                     bool use_rem_sets,
1188                     bool process_alloc_space_cards,
1189                     bool clear_alloc_space_cards)
1190       REQUIRES_SHARED(Locks::mutator_lock_);
1191 
1192   // Push an object onto the allocation stack.
1193   void PushOnAllocationStack(Thread* self, ObjPtr<mirror::Object>* obj)
1194       REQUIRES_SHARED(Locks::mutator_lock_)
1195       REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_);
1196   void PushOnAllocationStackWithInternalGC(Thread* self, ObjPtr<mirror::Object>* obj)
1197       REQUIRES_SHARED(Locks::mutator_lock_)
1198       REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_);
1199   void PushOnThreadLocalAllocationStackWithInternalGC(Thread* thread, ObjPtr<mirror::Object>* obj)
1200       REQUIRES_SHARED(Locks::mutator_lock_)
1201       REQUIRES(!*gc_complete_lock_, !*pending_task_lock_, !process_state_update_lock_);
1202 
1203   void ClearPendingTrim(Thread* self) REQUIRES(!*pending_task_lock_);
1204   void ClearPendingCollectorTransition(Thread* self) REQUIRES(!*pending_task_lock_);
1205 
1206   // What kind of concurrency behavior is the runtime after? Currently true for concurrent mark
1207   // sweep GC, false for other GC types.
IsGcConcurrent()1208   bool IsGcConcurrent() const ALWAYS_INLINE {
1209     return collector_type_ == kCollectorTypeCC ||
1210         collector_type_ == kCollectorTypeCMS ||
1211         collector_type_ == kCollectorTypeCCBackground;
1212   }
1213 
1214   // Trim the managed and native spaces by releasing unused memory back to the OS.
1215   void TrimSpaces(Thread* self) REQUIRES(!*gc_complete_lock_);
1216 
1217   // Trim 0 pages at the end of reference tables.
1218   void TrimIndirectReferenceTables(Thread* self);
1219 
1220   template <typename Visitor>
1221   ALWAYS_INLINE void VisitObjectsInternal(Visitor&& visitor)
1222       REQUIRES_SHARED(Locks::mutator_lock_)
1223       REQUIRES(!Locks::heap_bitmap_lock_, !*gc_complete_lock_);
1224   template <typename Visitor>
1225   ALWAYS_INLINE void VisitObjectsInternalRegionSpace(Visitor&& visitor)
1226       REQUIRES(Locks::mutator_lock_, !Locks::heap_bitmap_lock_, !*gc_complete_lock_);
1227 
1228   void UpdateGcCountRateHistograms() REQUIRES(gc_complete_lock_);
1229 
1230   // GC stress mode attempts to do one GC per unique backtrace.
1231   void CheckGcStressMode(Thread* self, ObjPtr<mirror::Object>* obj)
1232       REQUIRES_SHARED(Locks::mutator_lock_)
1233       REQUIRES(!*gc_complete_lock_, !*pending_task_lock_,
1234                !*backtrace_lock_, !process_state_update_lock_);
1235 
NonStickyGcType()1236   collector::GcType NonStickyGcType() const {
1237     return HasZygoteSpace() ? collector::kGcTypePartial : collector::kGcTypeFull;
1238   }
1239 
1240   // Return the amount of space we allow for native memory when deciding whether to
1241   // collect. We collect when a weighted sum of Java memory plus native memory exceeds
1242   // the similarly weighted sum of the Java heap size target and this value.
NativeAllocationGcWatermark()1243   ALWAYS_INLINE size_t NativeAllocationGcWatermark() const {
1244     // We keep the traditional limit of max_free_ in place for small heaps,
1245     // but allow it to be adjusted upward for large heaps to limit GC overhead.
1246     return target_footprint_.load(std::memory_order_relaxed) / 8 + max_free_;
1247   }
1248 
1249   ALWAYS_INLINE void IncrementNumberOfBytesFreedRevoke(size_t freed_bytes_revoke);
1250 
1251   // On switching app from background to foreground, grow the heap size
1252   // to incorporate foreground heap growth multiplier.
1253   void GrowHeapOnJankPerceptibleSwitch() REQUIRES(!process_state_update_lock_);
1254 
1255   // Update *_freed_ever_ counters to reflect current GC values.
1256   void IncrementFreedEver();
1257 
1258   // Remove a vlog code from heap-inl.h which is transitively included in half the world.
1259   static void VlogHeapGrowth(size_t max_allowed_footprint, size_t new_footprint, size_t alloc_size);
1260 
1261   // Return our best approximation of the number of bytes of native memory that
1262   // are currently in use, and could possibly be reclaimed as an indirect result
1263   // of a garbage collection.
1264   size_t GetNativeBytes();
1265 
1266   // All-known continuous spaces, where objects lie within fixed bounds.
1267   std::vector<space::ContinuousSpace*> continuous_spaces_ GUARDED_BY(Locks::mutator_lock_);
1268 
1269   // All-known discontinuous spaces, where objects may be placed throughout virtual memory.
1270   std::vector<space::DiscontinuousSpace*> discontinuous_spaces_ GUARDED_BY(Locks::mutator_lock_);
1271 
1272   // All-known alloc spaces, where objects may be or have been allocated.
1273   std::vector<space::AllocSpace*> alloc_spaces_;
1274 
1275   // A space where non-movable objects are allocated, when compaction is enabled it contains
1276   // Classes, ArtMethods, ArtFields, and non moving objects.
1277   space::MallocSpace* non_moving_space_;
1278 
1279   // Space which we use for the kAllocatorTypeROSAlloc.
1280   space::RosAllocSpace* rosalloc_space_;
1281 
1282   // Space which we use for the kAllocatorTypeDlMalloc.
1283   space::DlMallocSpace* dlmalloc_space_;
1284 
1285   // The main space is the space which the GC copies to and from on process state updates. This
1286   // space is typically either the dlmalloc_space_ or the rosalloc_space_.
1287   space::MallocSpace* main_space_;
1288 
1289   // The large object space we are currently allocating into.
1290   space::LargeObjectSpace* large_object_space_;
1291 
1292   // The card table, dirtied by the write barrier.
1293   std::unique_ptr<accounting::CardTable> card_table_;
1294 
1295   std::unique_ptr<accounting::ReadBarrierTable> rb_table_;
1296 
1297   // A mod-union table remembers all of the references from the it's space to other spaces.
1298   AllocationTrackingSafeMap<space::Space*, accounting::ModUnionTable*, kAllocatorTagHeap>
1299       mod_union_tables_;
1300 
1301   // A remembered set remembers all of the references from the it's space to the target space.
1302   AllocationTrackingSafeMap<space::Space*, accounting::RememberedSet*, kAllocatorTagHeap>
1303       remembered_sets_;
1304 
1305   // The current collector type.
1306   CollectorType collector_type_;
1307   // Which collector we use when the app is in the foreground.
1308   CollectorType foreground_collector_type_;
1309   // Which collector we will use when the app is notified of a transition to background.
1310   CollectorType background_collector_type_;
1311   // Desired collector type, heap trimming daemon transitions the heap if it is != collector_type_.
1312   CollectorType desired_collector_type_;
1313 
1314   // Lock which guards pending tasks.
1315   Mutex* pending_task_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
1316 
1317   // How many GC threads we may use for paused parts of garbage collection.
1318   const size_t parallel_gc_threads_;
1319 
1320   // How many GC threads we may use for unpaused parts of garbage collection.
1321   const size_t conc_gc_threads_;
1322 
1323   // Boolean for if we are in low memory mode.
1324   const bool low_memory_mode_;
1325 
1326   // If we get a pause longer than long pause log threshold, then we print out the GC after it
1327   // finishes.
1328   const size_t long_pause_log_threshold_;
1329 
1330   // If we get a GC longer than long GC log threshold, then we print out the GC after it finishes.
1331   const size_t long_gc_log_threshold_;
1332 
1333   // Starting time of the new process; meant to be used for measuring total process CPU time.
1334   uint64_t process_cpu_start_time_ns_;
1335 
1336   // Last time (before and after) GC started; meant to be used to measure the
1337   // duration between two GCs.
1338   uint64_t pre_gc_last_process_cpu_time_ns_;
1339   uint64_t post_gc_last_process_cpu_time_ns_;
1340 
1341   // allocated_bytes * (current_process_cpu_time - [pre|post]_gc_last_process_cpu_time)
1342   double pre_gc_weighted_allocated_bytes_;
1343   double post_gc_weighted_allocated_bytes_;
1344 
1345   // If we ignore the target footprint it lets the heap grow until it hits the heap capacity, this
1346   // is useful for benchmarking since it reduces time spent in GC to a low %.
1347   const bool ignore_target_footprint_;
1348 
1349   // If we are running tests or some other configurations we might not actually
1350   // want logs for explicit gcs since they can get spammy.
1351   const bool always_log_explicit_gcs_;
1352 
1353   // Lock which guards zygote space creation.
1354   Mutex zygote_creation_lock_;
1355 
1356   // Non-null iff we have a zygote space. Doesn't contain the large objects allocated before
1357   // zygote space creation.
1358   space::ZygoteSpace* zygote_space_;
1359 
1360   // Minimum allocation size of large object.
1361   size_t large_object_threshold_;
1362 
1363   // Guards access to the state of GC, associated conditional variable is used to signal when a GC
1364   // completes.
1365   Mutex* gc_complete_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
1366   std::unique_ptr<ConditionVariable> gc_complete_cond_ GUARDED_BY(gc_complete_lock_);
1367 
1368   // Used to synchronize between JNI critical calls and the thread flip of the CC collector.
1369   Mutex* thread_flip_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
1370   std::unique_ptr<ConditionVariable> thread_flip_cond_ GUARDED_BY(thread_flip_lock_);
1371   // This counter keeps track of how many threads are currently in a JNI critical section. This is
1372   // incremented once per thread even with nested enters.
1373   size_t disable_thread_flip_count_ GUARDED_BY(thread_flip_lock_);
1374   bool thread_flip_running_ GUARDED_BY(thread_flip_lock_);
1375 
1376   // Reference processor;
1377   std::unique_ptr<ReferenceProcessor> reference_processor_;
1378 
1379   // Task processor, proxies heap trim requests to the daemon threads.
1380   std::unique_ptr<TaskProcessor> task_processor_;
1381 
1382   // Collector type of the running GC.
1383   volatile CollectorType collector_type_running_ GUARDED_BY(gc_complete_lock_);
1384 
1385   // Cause of the last running GC.
1386   volatile GcCause last_gc_cause_ GUARDED_BY(gc_complete_lock_);
1387 
1388   // The thread currently running the GC.
1389   volatile Thread* thread_running_gc_ GUARDED_BY(gc_complete_lock_);
1390 
1391   // Last Gc type we ran. Used by WaitForConcurrentGc to know which Gc was waited on.
1392   volatile collector::GcType last_gc_type_ GUARDED_BY(gc_complete_lock_);
1393   collector::GcType next_gc_type_;
1394 
1395   // Maximum size that the heap can reach.
1396   size_t capacity_;
1397 
1398   // The size the heap is limited to. This is initially smaller than capacity, but for largeHeap
1399   // programs it is "cleared" making it the same as capacity.
1400   // Only weakly enforced for simultaneous allocations.
1401   size_t growth_limit_;
1402 
1403   // Target size (as in maximum allocatable bytes) for the heap. Weakly enforced as a limit for
1404   // non-concurrent GC. Used as a guideline for computing concurrent_start_bytes_ in the
1405   // concurrent GC case.
1406   Atomic<size_t> target_footprint_;
1407 
1408   // Computed with foreground-multiplier in GrowForUtilization() when run in
1409   // jank non-perceptible state. On update to process state from background to
1410   // foreground we set target_footprint_ to this value.
1411   Mutex process_state_update_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
1412   size_t min_foreground_target_footprint_ GUARDED_BY(process_state_update_lock_);
1413 
1414   // When num_bytes_allocated_ exceeds this amount then a concurrent GC should be requested so that
1415   // it completes ahead of an allocation failing.
1416   // A multiple of this is also used to determine when to trigger a GC in response to native
1417   // allocation.
1418   size_t concurrent_start_bytes_;
1419 
1420   // Since the heap was created, how many bytes have been freed.
1421   std::atomic<uint64_t> total_bytes_freed_ever_;
1422 
1423   // Since the heap was created, how many objects have been freed.
1424   std::atomic<uint64_t> total_objects_freed_ever_;
1425 
1426   // Number of bytes currently allocated and not yet reclaimed. Includes active
1427   // TLABS in their entirety, even if they have not yet been parceled out.
1428   Atomic<size_t> num_bytes_allocated_;
1429 
1430   // Number of registered native bytes allocated. Adjusted after each RegisterNativeAllocation and
1431   // RegisterNativeFree. Used to  help determine when to trigger GC for native allocations. Should
1432   // not include bytes allocated through the system malloc, since those are implicitly included.
1433   Atomic<size_t> native_bytes_registered_;
1434 
1435   // Approximately the smallest value of GetNativeBytes() we've seen since the last GC.
1436   Atomic<size_t> old_native_bytes_allocated_;
1437 
1438   // Total number of native objects of which we were notified since the beginning of time, mod 2^32.
1439   // Allows us to check for GC only roughly every kNotifyNativeInterval allocations.
1440   Atomic<uint32_t> native_objects_notified_;
1441 
1442   // Number of bytes freed by thread local buffer revokes. This will
1443   // cancel out the ahead-of-time bulk counting of bytes allocated in
1444   // rosalloc thread-local buffers.  It is temporarily accumulated
1445   // here to be subtracted from num_bytes_allocated_ later at the next
1446   // GC.
1447   Atomic<size_t> num_bytes_freed_revoke_;
1448 
1449   // Info related to the current or previous GC iteration.
1450   collector::Iteration current_gc_iteration_;
1451 
1452   // Heap verification flags.
1453   const bool verify_missing_card_marks_;
1454   const bool verify_system_weaks_;
1455   const bool verify_pre_gc_heap_;
1456   const bool verify_pre_sweeping_heap_;
1457   const bool verify_post_gc_heap_;
1458   const bool verify_mod_union_table_;
1459   bool verify_pre_gc_rosalloc_;
1460   bool verify_pre_sweeping_rosalloc_;
1461   bool verify_post_gc_rosalloc_;
1462   const bool gc_stress_mode_;
1463 
1464   // RAII that temporarily disables the rosalloc verification during
1465   // the zygote fork.
1466   class ScopedDisableRosAllocVerification {
1467    private:
1468     Heap* const heap_;
1469     const bool orig_verify_pre_gc_;
1470     const bool orig_verify_pre_sweeping_;
1471     const bool orig_verify_post_gc_;
1472 
1473    public:
ScopedDisableRosAllocVerification(Heap * heap)1474     explicit ScopedDisableRosAllocVerification(Heap* heap)
1475         : heap_(heap),
1476           orig_verify_pre_gc_(heap_->verify_pre_gc_rosalloc_),
1477           orig_verify_pre_sweeping_(heap_->verify_pre_sweeping_rosalloc_),
1478           orig_verify_post_gc_(heap_->verify_post_gc_rosalloc_) {
1479       heap_->verify_pre_gc_rosalloc_ = false;
1480       heap_->verify_pre_sweeping_rosalloc_ = false;
1481       heap_->verify_post_gc_rosalloc_ = false;
1482     }
~ScopedDisableRosAllocVerification()1483     ~ScopedDisableRosAllocVerification() {
1484       heap_->verify_pre_gc_rosalloc_ = orig_verify_pre_gc_;
1485       heap_->verify_pre_sweeping_rosalloc_ = orig_verify_pre_sweeping_;
1486       heap_->verify_post_gc_rosalloc_ = orig_verify_post_gc_;
1487     }
1488   };
1489 
1490   // Parallel GC data structures.
1491   std::unique_ptr<ThreadPool> thread_pool_;
1492 
1493   // A bitmap that is set corresponding to the known live objects since the last GC cycle.
1494   std::unique_ptr<accounting::HeapBitmap> live_bitmap_ GUARDED_BY(Locks::heap_bitmap_lock_);
1495   // A bitmap that is set corresponding to the marked objects in the current GC cycle.
1496   std::unique_ptr<accounting::HeapBitmap> mark_bitmap_ GUARDED_BY(Locks::heap_bitmap_lock_);
1497 
1498   // Mark stack that we reuse to avoid re-allocating the mark stack.
1499   std::unique_ptr<accounting::ObjectStack> mark_stack_;
1500 
1501   // Allocation stack, new allocations go here so that we can do sticky mark bits. This enables us
1502   // to use the live bitmap as the old mark bitmap.
1503   const size_t max_allocation_stack_size_;
1504   std::unique_ptr<accounting::ObjectStack> allocation_stack_;
1505 
1506   // Second allocation stack so that we can process allocation with the heap unlocked.
1507   std::unique_ptr<accounting::ObjectStack> live_stack_;
1508 
1509   // Allocator type.
1510   AllocatorType current_allocator_;
1511   const AllocatorType current_non_moving_allocator_;
1512 
1513   // Which GCs we run in order when an allocation fails.
1514   std::vector<collector::GcType> gc_plan_;
1515 
1516   // Bump pointer spaces.
1517   space::BumpPointerSpace* bump_pointer_space_;
1518   // Temp space is the space which the semispace collector copies to.
1519   space::BumpPointerSpace* temp_space_;
1520 
1521   // Region space, used by the concurrent collector.
1522   space::RegionSpace* region_space_;
1523 
1524   // Minimum free guarantees that you always have at least min_free_ free bytes after growing for
1525   // utilization, regardless of target utilization ratio.
1526   const size_t min_free_;
1527 
1528   // The ideal maximum free size, when we grow the heap for utilization.
1529   const size_t max_free_;
1530 
1531   // Target ideal heap utilization ratio.
1532   double target_utilization_;
1533 
1534   // How much more we grow the heap when we are a foreground app instead of background.
1535   double foreground_heap_growth_multiplier_;
1536 
1537   // The amount of native memory allocation since the last GC required to cause us to wait for a
1538   // collection as a result of native allocation. Very large values can cause the device to run
1539   // out of memory, due to lack of finalization to reclaim native memory.  Making it too small can
1540   // cause jank in apps like launcher that intentionally allocate large amounts of memory in rapid
1541   // succession. (b/122099093) 1/4 to 1/3 of physical memory seems to be a good number.
1542   const size_t stop_for_native_allocs_;
1543 
1544   // Total time which mutators are paused or waiting for GC to complete.
1545   uint64_t total_wait_time_;
1546 
1547   // The current state of heap verification, may be enabled or disabled.
1548   VerifyObjectMode verify_object_mode_;
1549 
1550   // Compacting GC disable count, prevents compacting GC from running iff > 0.
1551   size_t disable_moving_gc_count_ GUARDED_BY(gc_complete_lock_);
1552 
1553   std::vector<collector::GarbageCollector*> garbage_collectors_;
1554   collector::SemiSpace* semi_space_collector_;
1555   Atomic<collector::ConcurrentCopying*> active_concurrent_copying_collector_;
1556   collector::ConcurrentCopying* young_concurrent_copying_collector_;
1557   collector::ConcurrentCopying* concurrent_copying_collector_;
1558 
1559   const bool is_running_on_memory_tool_;
1560   const bool use_tlab_;
1561 
1562   // Pointer to the space which becomes the new main space when we do homogeneous space compaction.
1563   // Use unique_ptr since the space is only added during the homogeneous compaction phase.
1564   std::unique_ptr<space::MallocSpace> main_space_backup_;
1565 
1566   // Minimal interval allowed between two homogeneous space compactions caused by OOM.
1567   uint64_t min_interval_homogeneous_space_compaction_by_oom_;
1568 
1569   // Times of the last homogeneous space compaction caused by OOM.
1570   uint64_t last_time_homogeneous_space_compaction_by_oom_;
1571 
1572   // Saved OOMs by homogeneous space compaction.
1573   Atomic<size_t> count_delayed_oom_;
1574 
1575   // Count for requested homogeneous space compaction.
1576   Atomic<size_t> count_requested_homogeneous_space_compaction_;
1577 
1578   // Count for ignored homogeneous space compaction.
1579   Atomic<size_t> count_ignored_homogeneous_space_compaction_;
1580 
1581   // Count for performed homogeneous space compaction.
1582   Atomic<size_t> count_performed_homogeneous_space_compaction_;
1583 
1584   // The number of garbage collections (either young or full, not trims or the like) we have
1585   // completed since heap creation. We include requests that turned out to be impossible
1586   // because they were disabled. We guard against wrapping, though that's unlikely.
1587   // Increment is guarded by gc_complete_lock_.
1588   Atomic<uint32_t> gcs_completed_;
1589 
1590   // The number of the last garbage collection that has been requested.  A value of gcs_completed
1591   // + 1 indicates that another collection is needed or in progress. A value of gcs_completed_ or
1592   // (logically) less means that no new GC has been requested.
1593   Atomic<uint32_t> max_gc_requested_;
1594 
1595   // Active tasks which we can modify (change target time, desired collector type, etc..).
1596   CollectorTransitionTask* pending_collector_transition_ GUARDED_BY(pending_task_lock_);
1597   HeapTrimTask* pending_heap_trim_ GUARDED_BY(pending_task_lock_);
1598 
1599   // Whether or not we use homogeneous space compaction to avoid OOM errors.
1600   bool use_homogeneous_space_compaction_for_oom_;
1601 
1602   // If true, enable generational collection when using the Concurrent Copying
1603   // (CC) collector, i.e. use sticky-bit CC for minor collections and (full) CC
1604   // for major collections. Set in Heap constructor.
1605   const bool use_generational_cc_;
1606 
1607   // True if the currently running collection has made some thread wait.
1608   bool running_collection_is_blocking_ GUARDED_BY(gc_complete_lock_);
1609   // The number of blocking GC runs.
1610   uint64_t blocking_gc_count_;
1611   // The total duration of blocking GC runs.
1612   uint64_t blocking_gc_time_;
1613   // The duration of the window for the GC count rate histograms.
1614   static constexpr uint64_t kGcCountRateHistogramWindowDuration = MsToNs(10 * 1000);  // 10s.
1615   // Maximum number of missed histogram windows for which statistics will be collected.
1616   static constexpr uint64_t kGcCountRateHistogramMaxNumMissedWindows = 100;
1617   // The last time when the GC count rate histograms were updated.
1618   // This is rounded by kGcCountRateHistogramWindowDuration (a multiple of 10s).
1619   uint64_t last_update_time_gc_count_rate_histograms_;
1620   // The running count of GC runs in the last window.
1621   uint64_t gc_count_last_window_;
1622   // The running count of blocking GC runs in the last window.
1623   uint64_t blocking_gc_count_last_window_;
1624   // The maximum number of buckets in the GC count rate histograms.
1625   static constexpr size_t kGcCountRateMaxBucketCount = 200;
1626   // The histogram of the number of GC invocations per window duration.
1627   Histogram<uint64_t> gc_count_rate_histogram_ GUARDED_BY(gc_complete_lock_);
1628   // The histogram of the number of blocking GC invocations per window duration.
1629   Histogram<uint64_t> blocking_gc_count_rate_histogram_ GUARDED_BY(gc_complete_lock_);
1630 
1631   // Allocation tracking support
1632   Atomic<bool> alloc_tracking_enabled_;
1633   std::unique_ptr<AllocRecordObjectMap> allocation_records_;
1634   size_t alloc_record_depth_;
1635 
1636   // Perfetto Java Heap Profiler support.
1637   HeapSampler heap_sampler_;
1638 
1639   // GC stress related data structures.
1640   Mutex* backtrace_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
1641   // Debugging variables, seen backtraces vs unique backtraces.
1642   Atomic<uint64_t> seen_backtrace_count_;
1643   Atomic<uint64_t> unique_backtrace_count_;
1644   // Stack trace hashes that we already saw,
1645   std::unordered_set<uint64_t> seen_backtraces_ GUARDED_BY(backtrace_lock_);
1646 
1647   // We disable GC when we are shutting down the runtime in case there are daemon threads still
1648   // allocating.
1649   bool gc_disabled_for_shutdown_ GUARDED_BY(gc_complete_lock_);
1650 
1651   // Turned on by -XX:DumpRegionInfoBeforeGC and -XX:DumpRegionInfoAfterGC to
1652   // emit region info before and after each GC cycle.
1653   bool dump_region_info_before_gc_;
1654   bool dump_region_info_after_gc_;
1655 
1656   // Boot image spaces.
1657   std::vector<space::ImageSpace*> boot_image_spaces_;
1658 
1659   // Boot image address range. Includes images and oat files.
1660   uint32_t boot_images_start_address_;
1661   uint32_t boot_images_size_;
1662 
1663   // An installed allocation listener.
1664   Atomic<AllocationListener*> alloc_listener_;
1665   // An installed GC Pause listener.
1666   Atomic<GcPauseListener*> gc_pause_listener_;
1667 
1668   std::unique_ptr<Verification> verification_;
1669 
1670   friend class CollectorTransitionTask;
1671   friend class collector::GarbageCollector;
1672   friend class collector::ConcurrentCopying;
1673   friend class collector::MarkSweep;
1674   friend class collector::SemiSpace;
1675   friend class GCCriticalSection;
1676   friend class ReferenceQueue;
1677   friend class ScopedGCCriticalSection;
1678   friend class ScopedInterruptibleGCCriticalSection;
1679   friend class VerifyReferenceCardVisitor;
1680   friend class VerifyReferenceVisitor;
1681   friend class VerifyObjectVisitor;
1682 
1683   DISALLOW_IMPLICIT_CONSTRUCTORS(Heap);
1684 };
1685 
1686 }  // namespace gc
1687 }  // namespace art
1688 
1689 #endif  // ART_RUNTIME_GC_HEAP_H_
1690