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