1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "heap.h"
18 
19 #include <limits>
20 #include "android-base/thread_annotations.h"
21 #if defined(__BIONIC__) || defined(__GLIBC__)
22 #include <malloc.h>  // For mallinfo()
23 #endif
24 #include <memory>
25 #include <vector>
26 
27 #include "android-base/stringprintf.h"
28 
29 #include "allocation_listener.h"
30 #include "art_field-inl.h"
31 #include "backtrace_helper.h"
32 #include "base/allocator.h"
33 #include "base/arena_allocator.h"
34 #include "base/dumpable.h"
35 #include "base/file_utils.h"
36 #include "base/histogram-inl.h"
37 #include "base/logging.h"  // For VLOG.
38 #include "base/memory_tool.h"
39 #include "base/mutex.h"
40 #include "base/os.h"
41 #include "base/stl_util.h"
42 #include "base/systrace.h"
43 #include "base/time_utils.h"
44 #include "base/utils.h"
45 #include "class_root.h"
46 #include "common_throws.h"
47 #include "debugger.h"
48 #include "dex/dex_file-inl.h"
49 #include "entrypoints/quick/quick_alloc_entrypoints.h"
50 #include "gc/accounting/card_table-inl.h"
51 #include "gc/accounting/heap_bitmap-inl.h"
52 #include "gc/accounting/mod_union_table-inl.h"
53 #include "gc/accounting/read_barrier_table.h"
54 #include "gc/accounting/remembered_set.h"
55 #include "gc/accounting/space_bitmap-inl.h"
56 #include "gc/collector/concurrent_copying.h"
57 #include "gc/collector/mark_sweep.h"
58 #include "gc/collector/partial_mark_sweep.h"
59 #include "gc/collector/semi_space.h"
60 #include "gc/collector/sticky_mark_sweep.h"
61 #include "gc/racing_check.h"
62 #include "gc/reference_processor.h"
63 #include "gc/scoped_gc_critical_section.h"
64 #include "gc/space/bump_pointer_space.h"
65 #include "gc/space/dlmalloc_space-inl.h"
66 #include "gc/space/image_space.h"
67 #include "gc/space/large_object_space.h"
68 #include "gc/space/region_space.h"
69 #include "gc/space/rosalloc_space-inl.h"
70 #include "gc/space/space-inl.h"
71 #include "gc/space/zygote_space.h"
72 #include "gc/task_processor.h"
73 #include "gc/verification.h"
74 #include "gc_pause_listener.h"
75 #include "gc_root.h"
76 #include "handle_scope-inl.h"
77 #include "heap-inl.h"
78 #include "heap-visit-objects-inl.h"
79 #include "image.h"
80 #include "intern_table.h"
81 #include "jit/jit.h"
82 #include "jit/jit_code_cache.h"
83 #include "jni/java_vm_ext.h"
84 #include "mirror/class-inl.h"
85 #include "mirror/executable-inl.h"
86 #include "mirror/field.h"
87 #include "mirror/method_handle_impl.h"
88 #include "mirror/object-inl.h"
89 #include "mirror/object-refvisitor-inl.h"
90 #include "mirror/object_array-inl.h"
91 #include "mirror/reference-inl.h"
92 #include "mirror/var_handle.h"
93 #include "nativehelper/scoped_local_ref.h"
94 #include "obj_ptr-inl.h"
95 #include "reflection.h"
96 #include "runtime.h"
97 #include "scoped_thread_state_change-inl.h"
98 #include "thread_list.h"
99 #include "verify_object-inl.h"
100 #include "well_known_classes.h"
101 
102 namespace art {
103 
104 namespace gc {
105 
106 DEFINE_RUNTIME_DEBUG_FLAG(Heap, kStressCollectorTransition);
107 
108 // Minimum amount of remaining bytes before a concurrent GC is triggered.
109 static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
110 static constexpr size_t kMaxConcurrentRemainingBytes = 512 * KB;
111 // Sticky GC throughput adjustment, divided by 4. Increasing this causes sticky GC to occur more
112 // relative to partial/full GC. This may be desirable since sticky GCs interfere less with mutator
113 // threads (lower pauses, use less memory bandwidth).
GetStickyGcThroughputAdjustment(bool use_generational_cc)114 static double GetStickyGcThroughputAdjustment(bool use_generational_cc) {
115   return use_generational_cc ? 0.5 : 1.0;
116 }
117 // Whether or not we compact the zygote in PreZygoteFork.
118 static constexpr bool kCompactZygote = kMovingCollector;
119 // How many reserve entries are at the end of the allocation stack, these are only needed if the
120 // allocation stack overflows.
121 static constexpr size_t kAllocationStackReserveSize = 1024;
122 // Default mark stack size in bytes.
123 static const size_t kDefaultMarkStackSize = 64 * KB;
124 // Define space name.
125 static const char* kDlMallocSpaceName[2] = {"main dlmalloc space", "main dlmalloc space 1"};
126 static const char* kRosAllocSpaceName[2] = {"main rosalloc space", "main rosalloc space 1"};
127 static const char* kMemMapSpaceName[2] = {"main space", "main space 1"};
128 static const char* kNonMovingSpaceName = "non moving space";
129 static const char* kZygoteSpaceName = "zygote space";
130 static constexpr bool kGCALotMode = false;
131 // GC alot mode uses a small allocation stack to stress test a lot of GC.
132 static constexpr size_t kGcAlotAllocationStackSize = 4 * KB /
133     sizeof(mirror::HeapReference<mirror::Object>);
134 // Verify objet has a small allocation stack size since searching the allocation stack is slow.
135 static constexpr size_t kVerifyObjectAllocationStackSize = 16 * KB /
136     sizeof(mirror::HeapReference<mirror::Object>);
137 static constexpr size_t kDefaultAllocationStackSize = 8 * MB /
138     sizeof(mirror::HeapReference<mirror::Object>);
139 
140 // For deterministic compilation, we need the heap to be at a well-known address.
141 static constexpr uint32_t kAllocSpaceBeginForDeterministicAoT = 0x40000000;
142 // Dump the rosalloc stats on SIGQUIT.
143 static constexpr bool kDumpRosAllocStatsOnSigQuit = false;
144 
145 static const char* kRegionSpaceName = "main space (region space)";
146 
147 // If true, we log all GCs in the both the foreground and background. Used for debugging.
148 static constexpr bool kLogAllGCs = false;
149 
150 // Use Max heap for 2 seconds, this is smaller than the usual 5s window since we don't want to leave
151 // allocate with relaxed ergonomics for that long.
152 static constexpr size_t kPostForkMaxHeapDurationMS = 2000;
153 
154 #if defined(__LP64__) || !defined(ADDRESS_SANITIZER)
155 // 300 MB (0x12c00000) - (default non-moving space capacity).
156 uint8_t* const Heap::kPreferredAllocSpaceBegin =
157     reinterpret_cast<uint8_t*>(300 * MB - kDefaultNonMovingSpaceCapacity);
158 #else
159 #ifdef __ANDROID__
160 // For 32-bit Android, use 0x20000000 because asan reserves 0x04000000 - 0x20000000.
161 uint8_t* const Heap::kPreferredAllocSpaceBegin = reinterpret_cast<uint8_t*>(0x20000000);
162 #else
163 // For 32-bit host, use 0x40000000 because asan uses most of the space below this.
164 uint8_t* const Heap::kPreferredAllocSpaceBegin = reinterpret_cast<uint8_t*>(0x40000000);
165 #endif
166 #endif
167 
CareAboutPauseTimes()168 static inline bool CareAboutPauseTimes() {
169   return Runtime::Current()->InJankPerceptibleProcessState();
170 }
171 
VerifyBootImagesContiguity(const std::vector<gc::space::ImageSpace * > & image_spaces)172 static void VerifyBootImagesContiguity(const std::vector<gc::space::ImageSpace*>& image_spaces) {
173   uint32_t boot_image_size = 0u;
174   for (size_t i = 0u, num_spaces = image_spaces.size(); i != num_spaces; ) {
175     const ImageHeader& image_header = image_spaces[i]->GetImageHeader();
176     uint32_t reservation_size = image_header.GetImageReservationSize();
177     uint32_t image_count = image_header.GetImageSpaceCount();
178 
179     CHECK_NE(image_count, 0u);
180     CHECK_LE(image_count, num_spaces - i);
181     CHECK_NE(reservation_size, 0u);
182     for (size_t j = 1u; j != image_count; ++j) {
183       CHECK_EQ(image_spaces[i + j]->GetImageHeader().GetComponentCount(), 0u);
184       CHECK_EQ(image_spaces[i + j]->GetImageHeader().GetImageReservationSize(), 0u);
185     }
186 
187     // Check the start of the heap.
188     CHECK_EQ(image_spaces[0]->Begin() + boot_image_size, image_spaces[i]->Begin());
189     // Check contiguous layout of images and oat files.
190     const uint8_t* current_heap = image_spaces[i]->Begin();
191     const uint8_t* current_oat = image_spaces[i]->GetImageHeader().GetOatFileBegin();
192     for (size_t j = 0u; j != image_count; ++j) {
193       const ImageHeader& current_header = image_spaces[i + j]->GetImageHeader();
194       CHECK_EQ(current_heap, image_spaces[i + j]->Begin());
195       CHECK_EQ(current_oat, current_header.GetOatFileBegin());
196       current_heap += RoundUp(current_header.GetImageSize(), kPageSize);
197       CHECK_GT(current_header.GetOatFileEnd(), current_header.GetOatFileBegin());
198       current_oat = current_header.GetOatFileEnd();
199     }
200     // Check that oat files start at the end of images.
201     CHECK_EQ(current_heap, image_spaces[i]->GetImageHeader().GetOatFileBegin());
202     // Check that the reservation size equals the size of images and oat files.
203     CHECK_EQ(reservation_size, static_cast<size_t>(current_oat - image_spaces[i]->Begin()));
204 
205     boot_image_size += reservation_size;
206     i += image_count;
207   }
208 }
209 
Heap(size_t initial_size,size_t growth_limit,size_t min_free,size_t max_free,double target_utilization,double foreground_heap_growth_multiplier,size_t stop_for_native_allocs,size_t capacity,size_t non_moving_space_capacity,const std::vector<std::string> & boot_class_path,const std::vector<std::string> & boot_class_path_locations,const std::string & image_file_name,const InstructionSet image_instruction_set,CollectorType foreground_collector_type,CollectorType background_collector_type,space::LargeObjectSpaceType large_object_space_type,size_t large_object_threshold,size_t parallel_gc_threads,size_t conc_gc_threads,bool low_memory_mode,size_t long_pause_log_threshold,size_t long_gc_log_threshold,bool ignore_target_footprint,bool use_tlab,bool verify_pre_gc_heap,bool verify_pre_sweeping_heap,bool verify_post_gc_heap,bool verify_pre_gc_rosalloc,bool verify_pre_sweeping_rosalloc,bool verify_post_gc_rosalloc,bool gc_stress_mode,bool measure_gc_performance,bool use_homogeneous_space_compaction_for_oom,bool use_generational_cc,uint64_t min_interval_homogeneous_space_compaction_by_oom,bool dump_region_info_before_gc,bool dump_region_info_after_gc,space::ImageSpaceLoadingOrder image_space_loading_order)210 Heap::Heap(size_t initial_size,
211            size_t growth_limit,
212            size_t min_free,
213            size_t max_free,
214            double target_utilization,
215            double foreground_heap_growth_multiplier,
216            size_t stop_for_native_allocs,
217            size_t capacity,
218            size_t non_moving_space_capacity,
219            const std::vector<std::string>& boot_class_path,
220            const std::vector<std::string>& boot_class_path_locations,
221            const std::string& image_file_name,
222            const InstructionSet image_instruction_set,
223            CollectorType foreground_collector_type,
224            CollectorType background_collector_type,
225            space::LargeObjectSpaceType large_object_space_type,
226            size_t large_object_threshold,
227            size_t parallel_gc_threads,
228            size_t conc_gc_threads,
229            bool low_memory_mode,
230            size_t long_pause_log_threshold,
231            size_t long_gc_log_threshold,
232            bool ignore_target_footprint,
233            bool use_tlab,
234            bool verify_pre_gc_heap,
235            bool verify_pre_sweeping_heap,
236            bool verify_post_gc_heap,
237            bool verify_pre_gc_rosalloc,
238            bool verify_pre_sweeping_rosalloc,
239            bool verify_post_gc_rosalloc,
240            bool gc_stress_mode,
241            bool measure_gc_performance,
242            bool use_homogeneous_space_compaction_for_oom,
243            bool use_generational_cc,
244            uint64_t min_interval_homogeneous_space_compaction_by_oom,
245            bool dump_region_info_before_gc,
246            bool dump_region_info_after_gc,
247            space::ImageSpaceLoadingOrder image_space_loading_order)
248     : non_moving_space_(nullptr),
249       rosalloc_space_(nullptr),
250       dlmalloc_space_(nullptr),
251       main_space_(nullptr),
252       collector_type_(kCollectorTypeNone),
253       foreground_collector_type_(foreground_collector_type),
254       background_collector_type_(background_collector_type),
255       desired_collector_type_(foreground_collector_type_),
256       pending_task_lock_(nullptr),
257       parallel_gc_threads_(parallel_gc_threads),
258       conc_gc_threads_(conc_gc_threads),
259       low_memory_mode_(low_memory_mode),
260       long_pause_log_threshold_(long_pause_log_threshold),
261       long_gc_log_threshold_(long_gc_log_threshold),
262       process_cpu_start_time_ns_(ProcessCpuNanoTime()),
263       pre_gc_last_process_cpu_time_ns_(process_cpu_start_time_ns_),
264       post_gc_last_process_cpu_time_ns_(process_cpu_start_time_ns_),
265       pre_gc_weighted_allocated_bytes_(0.0),
266       post_gc_weighted_allocated_bytes_(0.0),
267       ignore_target_footprint_(ignore_target_footprint),
268       zygote_creation_lock_("zygote creation lock", kZygoteCreationLock),
269       zygote_space_(nullptr),
270       large_object_threshold_(large_object_threshold),
271       disable_thread_flip_count_(0),
272       thread_flip_running_(false),
273       collector_type_running_(kCollectorTypeNone),
274       last_gc_cause_(kGcCauseNone),
275       thread_running_gc_(nullptr),
276       last_gc_type_(collector::kGcTypeNone),
277       next_gc_type_(collector::kGcTypePartial),
278       capacity_(capacity),
279       growth_limit_(growth_limit),
280       target_footprint_(initial_size),
281       // Using kPostMonitorLock as a lock at kDefaultMutexLevel is acquired after
282       // this one.
283       process_state_update_lock_("process state update lock", kPostMonitorLock),
284       min_foreground_target_footprint_(0),
285       concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
286       total_bytes_freed_ever_(0),
287       total_objects_freed_ever_(0),
288       num_bytes_allocated_(0),
289       native_bytes_registered_(0),
290       old_native_bytes_allocated_(0),
291       native_objects_notified_(0),
292       num_bytes_freed_revoke_(0),
293       verify_missing_card_marks_(false),
294       verify_system_weaks_(false),
295       verify_pre_gc_heap_(verify_pre_gc_heap),
296       verify_pre_sweeping_heap_(verify_pre_sweeping_heap),
297       verify_post_gc_heap_(verify_post_gc_heap),
298       verify_mod_union_table_(false),
299       verify_pre_gc_rosalloc_(verify_pre_gc_rosalloc),
300       verify_pre_sweeping_rosalloc_(verify_pre_sweeping_rosalloc),
301       verify_post_gc_rosalloc_(verify_post_gc_rosalloc),
302       gc_stress_mode_(gc_stress_mode),
303       /* For GC a lot mode, we limit the allocation stacks to be kGcAlotInterval allocations. This
304        * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
305        * verification is enabled, we limit the size of allocation stacks to speed up their
306        * searching.
307        */
308       max_allocation_stack_size_(kGCALotMode ? kGcAlotAllocationStackSize
309           : (kVerifyObjectSupport > kVerifyObjectModeFast) ? kVerifyObjectAllocationStackSize :
310           kDefaultAllocationStackSize),
311       current_allocator_(kAllocatorTypeDlMalloc),
312       current_non_moving_allocator_(kAllocatorTypeNonMoving),
313       bump_pointer_space_(nullptr),
314       temp_space_(nullptr),
315       region_space_(nullptr),
316       min_free_(min_free),
317       max_free_(max_free),
318       target_utilization_(target_utilization),
319       foreground_heap_growth_multiplier_(foreground_heap_growth_multiplier),
320       stop_for_native_allocs_(stop_for_native_allocs),
321       total_wait_time_(0),
322       verify_object_mode_(kVerifyObjectModeDisabled),
323       disable_moving_gc_count_(0),
324       semi_space_collector_(nullptr),
325       active_concurrent_copying_collector_(nullptr),
326       young_concurrent_copying_collector_(nullptr),
327       concurrent_copying_collector_(nullptr),
328       is_running_on_memory_tool_(Runtime::Current()->IsRunningOnMemoryTool()),
329       use_tlab_(use_tlab),
330       main_space_backup_(nullptr),
331       min_interval_homogeneous_space_compaction_by_oom_(
332           min_interval_homogeneous_space_compaction_by_oom),
333       last_time_homogeneous_space_compaction_by_oom_(NanoTime()),
334       pending_collector_transition_(nullptr),
335       pending_heap_trim_(nullptr),
336       use_homogeneous_space_compaction_for_oom_(use_homogeneous_space_compaction_for_oom),
337       use_generational_cc_(use_generational_cc),
338       running_collection_is_blocking_(false),
339       blocking_gc_count_(0U),
340       blocking_gc_time_(0U),
341       last_update_time_gc_count_rate_histograms_(  // Round down by the window duration.
342           (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration),
343       gc_count_last_window_(0U),
344       blocking_gc_count_last_window_(0U),
345       gc_count_rate_histogram_("gc count rate histogram", 1U, kGcCountRateMaxBucketCount),
346       blocking_gc_count_rate_histogram_("blocking gc count rate histogram", 1U,
347                                         kGcCountRateMaxBucketCount),
348       alloc_tracking_enabled_(false),
349       alloc_record_depth_(AllocRecordObjectMap::kDefaultAllocStackDepth),
350       backtrace_lock_(nullptr),
351       seen_backtrace_count_(0u),
352       unique_backtrace_count_(0u),
353       gc_disabled_for_shutdown_(false),
354       dump_region_info_before_gc_(dump_region_info_before_gc),
355       dump_region_info_after_gc_(dump_region_info_after_gc),
356       boot_image_spaces_(),
357       boot_images_start_address_(0u),
358       boot_images_size_(0u) {
359   if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
360     LOG(INFO) << "Heap() entering";
361   }
362   if (kUseReadBarrier) {
363     CHECK_EQ(foreground_collector_type_, kCollectorTypeCC);
364     CHECK_EQ(background_collector_type_, kCollectorTypeCCBackground);
365   } else if (background_collector_type_ != gc::kCollectorTypeHomogeneousSpaceCompact) {
366     CHECK_EQ(IsMovingGc(foreground_collector_type_), IsMovingGc(background_collector_type_))
367         << "Changing from " << foreground_collector_type_ << " to "
368         << background_collector_type_ << " (or visa versa) is not supported.";
369   }
370   verification_.reset(new Verification(this));
371   CHECK_GE(large_object_threshold, kMinLargeObjectThreshold);
372   ScopedTrace trace(__FUNCTION__);
373   Runtime* const runtime = Runtime::Current();
374   // If we aren't the zygote, switch to the default non zygote allocator. This may update the
375   // entrypoints.
376   const bool is_zygote = runtime->IsZygote();
377   if (!is_zygote) {
378     // Background compaction is currently not supported for command line runs.
379     if (background_collector_type_ != foreground_collector_type_) {
380       VLOG(heap) << "Disabling background compaction for non zygote";
381       background_collector_type_ = foreground_collector_type_;
382     }
383   }
384   ChangeCollector(desired_collector_type_);
385   live_bitmap_.reset(new accounting::HeapBitmap(this));
386   mark_bitmap_.reset(new accounting::HeapBitmap(this));
387 
388   // We don't have hspace compaction enabled with CC.
389   if (foreground_collector_type_ == kCollectorTypeCC) {
390     use_homogeneous_space_compaction_for_oom_ = false;
391   }
392   bool support_homogeneous_space_compaction =
393       background_collector_type_ == gc::kCollectorTypeHomogeneousSpaceCompact ||
394       use_homogeneous_space_compaction_for_oom_;
395   // We may use the same space the main space for the non moving space if we don't need to compact
396   // from the main space.
397   // This is not the case if we support homogeneous compaction or have a moving background
398   // collector type.
399   bool separate_non_moving_space = is_zygote ||
400       support_homogeneous_space_compaction || IsMovingGc(foreground_collector_type_) ||
401       IsMovingGc(background_collector_type_);
402 
403   // Requested begin for the alloc space, to follow the mapped image and oat files
404   uint8_t* request_begin = nullptr;
405   // Calculate the extra space required after the boot image, see allocations below.
406   size_t heap_reservation_size = 0u;
407   if (separate_non_moving_space) {
408     heap_reservation_size = non_moving_space_capacity;
409   } else if (foreground_collector_type_ != kCollectorTypeCC && is_zygote) {
410     heap_reservation_size = capacity_;
411   }
412   heap_reservation_size = RoundUp(heap_reservation_size, kPageSize);
413   // Load image space(s).
414   std::vector<std::unique_ptr<space::ImageSpace>> boot_image_spaces;
415   MemMap heap_reservation;
416   if (space::ImageSpace::LoadBootImage(boot_class_path,
417                                        boot_class_path_locations,
418                                        image_file_name,
419                                        image_instruction_set,
420                                        image_space_loading_order,
421                                        runtime->ShouldRelocate(),
422                                        /*executable=*/ !runtime->IsAotCompiler(),
423                                        is_zygote,
424                                        heap_reservation_size,
425                                        &boot_image_spaces,
426                                        &heap_reservation)) {
427     DCHECK_EQ(heap_reservation_size, heap_reservation.IsValid() ? heap_reservation.Size() : 0u);
428     DCHECK(!boot_image_spaces.empty());
429     request_begin = boot_image_spaces.back()->GetImageHeader().GetOatFileEnd();
430     DCHECK(!heap_reservation.IsValid() || request_begin == heap_reservation.Begin())
431         << "request_begin=" << static_cast<const void*>(request_begin)
432         << " heap_reservation.Begin()=" << static_cast<const void*>(heap_reservation.Begin());
433     for (std::unique_ptr<space::ImageSpace>& space : boot_image_spaces) {
434       boot_image_spaces_.push_back(space.get());
435       AddSpace(space.release());
436     }
437     boot_images_start_address_ = PointerToLowMemUInt32(boot_image_spaces_.front()->Begin());
438     uint32_t boot_images_end =
439         PointerToLowMemUInt32(boot_image_spaces_.back()->GetImageHeader().GetOatFileEnd());
440     boot_images_size_ = boot_images_end - boot_images_start_address_;
441     if (kIsDebugBuild) {
442       VerifyBootImagesContiguity(boot_image_spaces_);
443     }
444   } else {
445     if (foreground_collector_type_ == kCollectorTypeCC) {
446       // Need to use a low address so that we can allocate a contiguous 2 * Xmx space
447       // when there's no image (dex2oat for target).
448       request_begin = kPreferredAllocSpaceBegin;
449     }
450     // Gross hack to make dex2oat deterministic.
451     if (foreground_collector_type_ == kCollectorTypeMS && Runtime::Current()->IsAotCompiler()) {
452       // Currently only enabled for MS collector since that is what the deterministic dex2oat uses.
453       // b/26849108
454       request_begin = reinterpret_cast<uint8_t*>(kAllocSpaceBeginForDeterministicAoT);
455     }
456   }
457 
458   /*
459   requested_alloc_space_begin ->     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
460                                      +-  nonmoving space (non_moving_space_capacity)+-
461                                      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
462                                      +-????????????????????????????????????????????+-
463                                      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
464                                      +-main alloc space / bump space 1 (capacity_) +-
465                                      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
466                                      +-????????????????????????????????????????????+-
467                                      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
468                                      +-main alloc space2 / bump space 2 (capacity_)+-
469                                      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
470   */
471 
472   MemMap main_mem_map_1;
473   MemMap main_mem_map_2;
474 
475   std::string error_str;
476   MemMap non_moving_space_mem_map;
477   if (separate_non_moving_space) {
478     ScopedTrace trace2("Create separate non moving space");
479     // If we are the zygote, the non moving space becomes the zygote space when we run
480     // PreZygoteFork the first time. In this case, call the map "zygote space" since we can't
481     // rename the mem map later.
482     const char* space_name = is_zygote ? kZygoteSpaceName : kNonMovingSpaceName;
483     // Reserve the non moving mem map before the other two since it needs to be at a specific
484     // address.
485     DCHECK_EQ(heap_reservation.IsValid(), !boot_image_spaces_.empty());
486     if (heap_reservation.IsValid()) {
487       non_moving_space_mem_map = heap_reservation.RemapAtEnd(
488           heap_reservation.Begin(), space_name, PROT_READ | PROT_WRITE, &error_str);
489     } else {
490       non_moving_space_mem_map = MapAnonymousPreferredAddress(
491           space_name, request_begin, non_moving_space_capacity, &error_str);
492     }
493     CHECK(non_moving_space_mem_map.IsValid()) << error_str;
494     DCHECK(!heap_reservation.IsValid());
495     // Try to reserve virtual memory at a lower address if we have a separate non moving space.
496     request_begin = kPreferredAllocSpaceBegin + non_moving_space_capacity;
497   }
498   // Attempt to create 2 mem maps at or after the requested begin.
499   if (foreground_collector_type_ != kCollectorTypeCC) {
500     ScopedTrace trace2("Create main mem map");
501     if (separate_non_moving_space || !is_zygote) {
502       main_mem_map_1 = MapAnonymousPreferredAddress(
503           kMemMapSpaceName[0], request_begin, capacity_, &error_str);
504     } else {
505       // If no separate non-moving space and we are the zygote, the main space must come right after
506       // the image space to avoid a gap. This is required since we want the zygote space to be
507       // adjacent to the image space.
508       DCHECK_EQ(heap_reservation.IsValid(), !boot_image_spaces_.empty());
509       main_mem_map_1 = MemMap::MapAnonymous(
510           kMemMapSpaceName[0],
511           request_begin,
512           capacity_,
513           PROT_READ | PROT_WRITE,
514           /* low_4gb= */ true,
515           /* reuse= */ false,
516           heap_reservation.IsValid() ? &heap_reservation : nullptr,
517           &error_str);
518     }
519     CHECK(main_mem_map_1.IsValid()) << error_str;
520     DCHECK(!heap_reservation.IsValid());
521   }
522   if (support_homogeneous_space_compaction ||
523       background_collector_type_ == kCollectorTypeSS ||
524       foreground_collector_type_ == kCollectorTypeSS) {
525     ScopedTrace trace2("Create main mem map 2");
526     main_mem_map_2 = MapAnonymousPreferredAddress(
527         kMemMapSpaceName[1], main_mem_map_1.End(), capacity_, &error_str);
528     CHECK(main_mem_map_2.IsValid()) << error_str;
529   }
530 
531   // Create the non moving space first so that bitmaps don't take up the address range.
532   if (separate_non_moving_space) {
533     ScopedTrace trace2("Add non moving space");
534     // Non moving space is always dlmalloc since we currently don't have support for multiple
535     // active rosalloc spaces.
536     const size_t size = non_moving_space_mem_map.Size();
537     const void* non_moving_space_mem_map_begin = non_moving_space_mem_map.Begin();
538     non_moving_space_ = space::DlMallocSpace::CreateFromMemMap(std::move(non_moving_space_mem_map),
539                                                                "zygote / non moving space",
540                                                                kDefaultStartingSize,
541                                                                initial_size,
542                                                                size,
543                                                                size,
544                                                                /* can_move_objects= */ false);
545     CHECK(non_moving_space_ != nullptr) << "Failed creating non moving space "
546         << non_moving_space_mem_map_begin;
547     non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
548     AddSpace(non_moving_space_);
549   }
550   // Create other spaces based on whether or not we have a moving GC.
551   if (foreground_collector_type_ == kCollectorTypeCC) {
552     CHECK(separate_non_moving_space);
553     // Reserve twice the capacity, to allow evacuating every region for explicit GCs.
554     MemMap region_space_mem_map =
555         space::RegionSpace::CreateMemMap(kRegionSpaceName, capacity_ * 2, request_begin);
556     CHECK(region_space_mem_map.IsValid()) << "No region space mem map";
557     region_space_ = space::RegionSpace::Create(
558         kRegionSpaceName, std::move(region_space_mem_map), use_generational_cc_);
559     AddSpace(region_space_);
560   } else if (IsMovingGc(foreground_collector_type_)) {
561     // Create bump pointer spaces.
562     // We only to create the bump pointer if the foreground collector is a compacting GC.
563     // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
564     bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 1",
565                                                                     std::move(main_mem_map_1));
566     CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
567     AddSpace(bump_pointer_space_);
568     temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
569                                                             std::move(main_mem_map_2));
570     CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
571     AddSpace(temp_space_);
572     CHECK(separate_non_moving_space);
573   } else {
574     CreateMainMallocSpace(std::move(main_mem_map_1), initial_size, growth_limit_, capacity_);
575     CHECK(main_space_ != nullptr);
576     AddSpace(main_space_);
577     if (!separate_non_moving_space) {
578       non_moving_space_ = main_space_;
579       CHECK(!non_moving_space_->CanMoveObjects());
580     }
581     if (main_mem_map_2.IsValid()) {
582       const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
583       main_space_backup_.reset(CreateMallocSpaceFromMemMap(std::move(main_mem_map_2),
584                                                            initial_size,
585                                                            growth_limit_,
586                                                            capacity_,
587                                                            name,
588                                                            /* can_move_objects= */ true));
589       CHECK(main_space_backup_.get() != nullptr);
590       // Add the space so its accounted for in the heap_begin and heap_end.
591       AddSpace(main_space_backup_.get());
592     }
593   }
594   CHECK(non_moving_space_ != nullptr);
595   CHECK(!non_moving_space_->CanMoveObjects());
596   // Allocate the large object space.
597   if (large_object_space_type == space::LargeObjectSpaceType::kFreeList) {
598     large_object_space_ = space::FreeListSpace::Create("free list large object space", capacity_);
599     CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
600   } else if (large_object_space_type == space::LargeObjectSpaceType::kMap) {
601     large_object_space_ = space::LargeObjectMapSpace::Create("mem map large object space");
602     CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
603   } else {
604     // Disable the large object space by making the cutoff excessively large.
605     large_object_threshold_ = std::numeric_limits<size_t>::max();
606     large_object_space_ = nullptr;
607   }
608   if (large_object_space_ != nullptr) {
609     AddSpace(large_object_space_);
610   }
611   // Compute heap capacity. Continuous spaces are sorted in order of Begin().
612   CHECK(!continuous_spaces_.empty());
613   // Relies on the spaces being sorted.
614   uint8_t* heap_begin = continuous_spaces_.front()->Begin();
615   uint8_t* heap_end = continuous_spaces_.back()->Limit();
616   size_t heap_capacity = heap_end - heap_begin;
617   // Remove the main backup space since it slows down the GC to have unused extra spaces.
618   // TODO: Avoid needing to do this.
619   if (main_space_backup_.get() != nullptr) {
620     RemoveSpace(main_space_backup_.get());
621   }
622   // Allocate the card table.
623   // We currently don't support dynamically resizing the card table.
624   // Since we don't know where in the low_4gb the app image will be located, make the card table
625   // cover the whole low_4gb. TODO: Extend the card table in AddSpace.
626   UNUSED(heap_capacity);
627   // Start at 4 KB, we can be sure there are no spaces mapped this low since the address range is
628   // reserved by the kernel.
629   static constexpr size_t kMinHeapAddress = 4 * KB;
630   card_table_.reset(accounting::CardTable::Create(reinterpret_cast<uint8_t*>(kMinHeapAddress),
631                                                   4 * GB - kMinHeapAddress));
632   CHECK(card_table_.get() != nullptr) << "Failed to create card table";
633   if (foreground_collector_type_ == kCollectorTypeCC && kUseTableLookupReadBarrier) {
634     rb_table_.reset(new accounting::ReadBarrierTable());
635     DCHECK(rb_table_->IsAllCleared());
636   }
637   if (HasBootImageSpace()) {
638     // Don't add the image mod union table if we are running without an image, this can crash if
639     // we use the CardCache implementation.
640     for (space::ImageSpace* image_space : GetBootImageSpaces()) {
641       accounting::ModUnionTable* mod_union_table = new accounting::ModUnionTableToZygoteAllocspace(
642           "Image mod-union table", this, image_space);
643       CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
644       AddModUnionTable(mod_union_table);
645     }
646   }
647   if (collector::SemiSpace::kUseRememberedSet && non_moving_space_ != main_space_) {
648     accounting::RememberedSet* non_moving_space_rem_set =
649         new accounting::RememberedSet("Non-moving space remembered set", this, non_moving_space_);
650     CHECK(non_moving_space_rem_set != nullptr) << "Failed to create non-moving space remembered set";
651     AddRememberedSet(non_moving_space_rem_set);
652   }
653   // TODO: Count objects in the image space here?
654   num_bytes_allocated_.store(0, std::memory_order_relaxed);
655   mark_stack_.reset(accounting::ObjectStack::Create("mark stack", kDefaultMarkStackSize,
656                                                     kDefaultMarkStackSize));
657   const size_t alloc_stack_capacity = max_allocation_stack_size_ + kAllocationStackReserveSize;
658   allocation_stack_.reset(accounting::ObjectStack::Create(
659       "allocation stack", max_allocation_stack_size_, alloc_stack_capacity));
660   live_stack_.reset(accounting::ObjectStack::Create(
661       "live stack", max_allocation_stack_size_, alloc_stack_capacity));
662   // It's still too early to take a lock because there are no threads yet, but we can create locks
663   // now. We don't create it earlier to make it clear that you can't use locks during heap
664   // initialization.
665   gc_complete_lock_ = new Mutex("GC complete lock");
666   gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
667                                                 *gc_complete_lock_));
668 
669   thread_flip_lock_ = new Mutex("GC thread flip lock");
670   thread_flip_cond_.reset(new ConditionVariable("GC thread flip condition variable",
671                                                 *thread_flip_lock_));
672   task_processor_.reset(new TaskProcessor());
673   reference_processor_.reset(new ReferenceProcessor());
674   pending_task_lock_ = new Mutex("Pending task lock");
675   if (ignore_target_footprint_) {
676     SetIdealFootprint(std::numeric_limits<size_t>::max());
677     concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
678   }
679   CHECK_NE(target_footprint_.load(std::memory_order_relaxed), 0U);
680   // Create our garbage collectors.
681   for (size_t i = 0; i < 2; ++i) {
682     const bool concurrent = i != 0;
683     if ((MayUseCollector(kCollectorTypeCMS) && concurrent) ||
684         (MayUseCollector(kCollectorTypeMS) && !concurrent)) {
685       garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
686       garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
687       garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
688     }
689   }
690   if (kMovingCollector) {
691     if (MayUseCollector(kCollectorTypeSS) ||
692         MayUseCollector(kCollectorTypeHomogeneousSpaceCompact) ||
693         use_homogeneous_space_compaction_for_oom_) {
694       semi_space_collector_ = new collector::SemiSpace(this);
695       garbage_collectors_.push_back(semi_space_collector_);
696     }
697     if (MayUseCollector(kCollectorTypeCC)) {
698       concurrent_copying_collector_ = new collector::ConcurrentCopying(this,
699                                                                        /*young_gen=*/false,
700                                                                        use_generational_cc_,
701                                                                        "",
702                                                                        measure_gc_performance);
703       if (use_generational_cc_) {
704         young_concurrent_copying_collector_ = new collector::ConcurrentCopying(
705             this,
706             /*young_gen=*/true,
707             use_generational_cc_,
708             "young",
709             measure_gc_performance);
710       }
711       active_concurrent_copying_collector_ = concurrent_copying_collector_;
712       DCHECK(region_space_ != nullptr);
713       concurrent_copying_collector_->SetRegionSpace(region_space_);
714       if (use_generational_cc_) {
715         young_concurrent_copying_collector_->SetRegionSpace(region_space_);
716         // At this point, non-moving space should be created.
717         DCHECK(non_moving_space_ != nullptr);
718         concurrent_copying_collector_->CreateInterRegionRefBitmaps();
719       }
720       garbage_collectors_.push_back(concurrent_copying_collector_);
721       if (use_generational_cc_) {
722         garbage_collectors_.push_back(young_concurrent_copying_collector_);
723       }
724     }
725   }
726   if (!GetBootImageSpaces().empty() && non_moving_space_ != nullptr &&
727       (is_zygote || separate_non_moving_space)) {
728     // Check that there's no gap between the image space and the non moving space so that the
729     // immune region won't break (eg. due to a large object allocated in the gap). This is only
730     // required when we're the zygote.
731     // Space with smallest Begin().
732     space::ImageSpace* first_space = nullptr;
733     for (space::ImageSpace* space : boot_image_spaces_) {
734       if (first_space == nullptr || space->Begin() < first_space->Begin()) {
735         first_space = space;
736       }
737     }
738     bool no_gap = MemMap::CheckNoGaps(*first_space->GetMemMap(), *non_moving_space_->GetMemMap());
739     if (!no_gap) {
740       PrintFileToLog("/proc/self/maps", LogSeverity::ERROR);
741       MemMap::DumpMaps(LOG_STREAM(ERROR), /* terse= */ true);
742       LOG(FATAL) << "There's a gap between the image space and the non-moving space";
743     }
744   }
745   instrumentation::Instrumentation* const instrumentation = runtime->GetInstrumentation();
746   if (gc_stress_mode_) {
747     backtrace_lock_ = new Mutex("GC complete lock");
748   }
749   if (is_running_on_memory_tool_ || gc_stress_mode_) {
750     instrumentation->InstrumentQuickAllocEntryPoints();
751   }
752   if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
753     LOG(INFO) << "Heap() exiting";
754   }
755 }
756 
MapAnonymousPreferredAddress(const char * name,uint8_t * request_begin,size_t capacity,std::string * out_error_str)757 MemMap Heap::MapAnonymousPreferredAddress(const char* name,
758                                           uint8_t* request_begin,
759                                           size_t capacity,
760                                           std::string* out_error_str) {
761   while (true) {
762     MemMap map = MemMap::MapAnonymous(name,
763                                       request_begin,
764                                       capacity,
765                                       PROT_READ | PROT_WRITE,
766                                       /*low_4gb=*/ true,
767                                       /*reuse=*/ false,
768                                       /*reservation=*/ nullptr,
769                                       out_error_str);
770     if (map.IsValid() || request_begin == nullptr) {
771       return map;
772     }
773     // Retry a  second time with no specified request begin.
774     request_begin = nullptr;
775   }
776 }
777 
MayUseCollector(CollectorType type) const778 bool Heap::MayUseCollector(CollectorType type) const {
779   return foreground_collector_type_ == type || background_collector_type_ == type;
780 }
781 
CreateMallocSpaceFromMemMap(MemMap && mem_map,size_t initial_size,size_t growth_limit,size_t capacity,const char * name,bool can_move_objects)782 space::MallocSpace* Heap::CreateMallocSpaceFromMemMap(MemMap&& mem_map,
783                                                       size_t initial_size,
784                                                       size_t growth_limit,
785                                                       size_t capacity,
786                                                       const char* name,
787                                                       bool can_move_objects) {
788   space::MallocSpace* malloc_space = nullptr;
789   if (kUseRosAlloc) {
790     // Create rosalloc space.
791     malloc_space = space::RosAllocSpace::CreateFromMemMap(std::move(mem_map),
792                                                           name,
793                                                           kDefaultStartingSize,
794                                                           initial_size,
795                                                           growth_limit,
796                                                           capacity,
797                                                           low_memory_mode_,
798                                                           can_move_objects);
799   } else {
800     malloc_space = space::DlMallocSpace::CreateFromMemMap(std::move(mem_map),
801                                                           name,
802                                                           kDefaultStartingSize,
803                                                           initial_size,
804                                                           growth_limit,
805                                                           capacity,
806                                                           can_move_objects);
807   }
808   if (collector::SemiSpace::kUseRememberedSet) {
809     accounting::RememberedSet* rem_set  =
810         new accounting::RememberedSet(std::string(name) + " remembered set", this, malloc_space);
811     CHECK(rem_set != nullptr) << "Failed to create main space remembered set";
812     AddRememberedSet(rem_set);
813   }
814   CHECK(malloc_space != nullptr) << "Failed to create " << name;
815   malloc_space->SetFootprintLimit(malloc_space->Capacity());
816   return malloc_space;
817 }
818 
CreateMainMallocSpace(MemMap && mem_map,size_t initial_size,size_t growth_limit,size_t capacity)819 void Heap::CreateMainMallocSpace(MemMap&& mem_map,
820                                  size_t initial_size,
821                                  size_t growth_limit,
822                                  size_t capacity) {
823   // Is background compaction is enabled?
824   bool can_move_objects = IsMovingGc(background_collector_type_) !=
825       IsMovingGc(foreground_collector_type_) || use_homogeneous_space_compaction_for_oom_;
826   // If we are the zygote and don't yet have a zygote space, it means that the zygote fork will
827   // happen in the future. If this happens and we have kCompactZygote enabled we wish to compact
828   // from the main space to the zygote space. If background compaction is enabled, always pass in
829   // that we can move objets.
830   if (kCompactZygote && Runtime::Current()->IsZygote() && !can_move_objects) {
831     // After the zygote we want this to be false if we don't have background compaction enabled so
832     // that getting primitive array elements is faster.
833     can_move_objects = !HasZygoteSpace();
834   }
835   if (collector::SemiSpace::kUseRememberedSet && main_space_ != nullptr) {
836     RemoveRememberedSet(main_space_);
837   }
838   const char* name = kUseRosAlloc ? kRosAllocSpaceName[0] : kDlMallocSpaceName[0];
839   main_space_ = CreateMallocSpaceFromMemMap(std::move(mem_map),
840                                             initial_size,
841                                             growth_limit,
842                                             capacity, name,
843                                             can_move_objects);
844   SetSpaceAsDefault(main_space_);
845   VLOG(heap) << "Created main space " << main_space_;
846 }
847 
ChangeAllocator(AllocatorType allocator)848 void Heap::ChangeAllocator(AllocatorType allocator) {
849   if (current_allocator_ != allocator) {
850     // These two allocators are only used internally and don't have any entrypoints.
851     CHECK_NE(allocator, kAllocatorTypeLOS);
852     CHECK_NE(allocator, kAllocatorTypeNonMoving);
853     current_allocator_ = allocator;
854     MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
855     SetQuickAllocEntryPointsAllocator(current_allocator_);
856     Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
857   }
858 }
859 
IsCompilingBoot() const860 bool Heap::IsCompilingBoot() const {
861   if (!Runtime::Current()->IsAotCompiler()) {
862     return false;
863   }
864   ScopedObjectAccess soa(Thread::Current());
865   for (const auto& space : continuous_spaces_) {
866     if (space->IsImageSpace() || space->IsZygoteSpace()) {
867       return false;
868     }
869   }
870   return true;
871 }
872 
IncrementDisableMovingGC(Thread * self)873 void Heap::IncrementDisableMovingGC(Thread* self) {
874   // Need to do this holding the lock to prevent races where the GC is about to run / running when
875   // we attempt to disable it.
876   ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
877   MutexLock mu(self, *gc_complete_lock_);
878   ++disable_moving_gc_count_;
879   if (IsMovingGc(collector_type_running_)) {
880     WaitForGcToCompleteLocked(kGcCauseDisableMovingGc, self);
881   }
882 }
883 
DecrementDisableMovingGC(Thread * self)884 void Heap::DecrementDisableMovingGC(Thread* self) {
885   MutexLock mu(self, *gc_complete_lock_);
886   CHECK_GT(disable_moving_gc_count_, 0U);
887   --disable_moving_gc_count_;
888 }
889 
IncrementDisableThreadFlip(Thread * self)890 void Heap::IncrementDisableThreadFlip(Thread* self) {
891   // Supposed to be called by mutators. If thread_flip_running_ is true, block. Otherwise, go ahead.
892   CHECK(kUseReadBarrier);
893   bool is_nested = self->GetDisableThreadFlipCount() > 0;
894   self->IncrementDisableThreadFlipCount();
895   if (is_nested) {
896     // If this is a nested JNI critical section enter, we don't need to wait or increment the global
897     // counter. The global counter is incremented only once for a thread for the outermost enter.
898     return;
899   }
900   ScopedThreadStateChange tsc(self, kWaitingForGcThreadFlip);
901   MutexLock mu(self, *thread_flip_lock_);
902   thread_flip_cond_->CheckSafeToWait(self);
903   bool has_waited = false;
904   uint64_t wait_start = NanoTime();
905   if (thread_flip_running_) {
906     ScopedTrace trace("IncrementDisableThreadFlip");
907     while (thread_flip_running_) {
908       has_waited = true;
909       thread_flip_cond_->Wait(self);
910     }
911   }
912   ++disable_thread_flip_count_;
913   if (has_waited) {
914     uint64_t wait_time = NanoTime() - wait_start;
915     total_wait_time_ += wait_time;
916     if (wait_time > long_pause_log_threshold_) {
917       LOG(INFO) << __FUNCTION__ << " blocked for " << PrettyDuration(wait_time);
918     }
919   }
920 }
921 
DecrementDisableThreadFlip(Thread * self)922 void Heap::DecrementDisableThreadFlip(Thread* self) {
923   // Supposed to be called by mutators. Decrement disable_thread_flip_count_ and potentially wake up
924   // the GC waiting before doing a thread flip.
925   CHECK(kUseReadBarrier);
926   self->DecrementDisableThreadFlipCount();
927   bool is_outermost = self->GetDisableThreadFlipCount() == 0;
928   if (!is_outermost) {
929     // If this is not an outermost JNI critical exit, we don't need to decrement the global counter.
930     // The global counter is decremented only once for a thread for the outermost exit.
931     return;
932   }
933   MutexLock mu(self, *thread_flip_lock_);
934   CHECK_GT(disable_thread_flip_count_, 0U);
935   --disable_thread_flip_count_;
936   if (disable_thread_flip_count_ == 0) {
937     // Potentially notify the GC thread blocking to begin a thread flip.
938     thread_flip_cond_->Broadcast(self);
939   }
940 }
941 
ThreadFlipBegin(Thread * self)942 void Heap::ThreadFlipBegin(Thread* self) {
943   // Supposed to be called by GC. Set thread_flip_running_ to be true. If disable_thread_flip_count_
944   // > 0, block. Otherwise, go ahead.
945   CHECK(kUseReadBarrier);
946   ScopedThreadStateChange tsc(self, kWaitingForGcThreadFlip);
947   MutexLock mu(self, *thread_flip_lock_);
948   thread_flip_cond_->CheckSafeToWait(self);
949   bool has_waited = false;
950   uint64_t wait_start = NanoTime();
951   CHECK(!thread_flip_running_);
952   // Set this to true before waiting so that frequent JNI critical enter/exits won't starve
953   // GC. This like a writer preference of a reader-writer lock.
954   thread_flip_running_ = true;
955   while (disable_thread_flip_count_ > 0) {
956     has_waited = true;
957     thread_flip_cond_->Wait(self);
958   }
959   if (has_waited) {
960     uint64_t wait_time = NanoTime() - wait_start;
961     total_wait_time_ += wait_time;
962     if (wait_time > long_pause_log_threshold_) {
963       LOG(INFO) << __FUNCTION__ << " blocked for " << PrettyDuration(wait_time);
964     }
965   }
966 }
967 
ThreadFlipEnd(Thread * self)968 void Heap::ThreadFlipEnd(Thread* self) {
969   // Supposed to be called by GC. Set thread_flip_running_ to false and potentially wake up mutators
970   // waiting before doing a JNI critical.
971   CHECK(kUseReadBarrier);
972   MutexLock mu(self, *thread_flip_lock_);
973   CHECK(thread_flip_running_);
974   thread_flip_running_ = false;
975   // Potentially notify mutator threads blocking to enter a JNI critical section.
976   thread_flip_cond_->Broadcast(self);
977 }
978 
GrowHeapOnJankPerceptibleSwitch()979 void Heap::GrowHeapOnJankPerceptibleSwitch() {
980   MutexLock mu(Thread::Current(), process_state_update_lock_);
981   size_t orig_target_footprint = target_footprint_.load(std::memory_order_relaxed);
982   if (orig_target_footprint < min_foreground_target_footprint_) {
983     target_footprint_.compare_exchange_strong(orig_target_footprint,
984                                               min_foreground_target_footprint_,
985                                               std::memory_order_relaxed);
986   }
987   min_foreground_target_footprint_ = 0;
988 }
989 
UpdateProcessState(ProcessState old_process_state,ProcessState new_process_state)990 void Heap::UpdateProcessState(ProcessState old_process_state, ProcessState new_process_state) {
991   if (old_process_state != new_process_state) {
992     const bool jank_perceptible = new_process_state == kProcessStateJankPerceptible;
993     if (jank_perceptible) {
994       // Transition back to foreground right away to prevent jank.
995       RequestCollectorTransition(foreground_collector_type_, 0);
996       GrowHeapOnJankPerceptibleSwitch();
997     } else {
998       // Don't delay for debug builds since we may want to stress test the GC.
999       // If background_collector_type_ is kCollectorTypeHomogeneousSpaceCompact then we have
1000       // special handling which does a homogenous space compaction once but then doesn't transition
1001       // the collector. Similarly, we invoke a full compaction for kCollectorTypeCC but don't
1002       // transition the collector.
1003       RequestCollectorTransition(background_collector_type_,
1004                                  kStressCollectorTransition
1005                                      ? 0
1006                                      : kCollectorTransitionWait);
1007     }
1008   }
1009 }
1010 
CreateThreadPool()1011 void Heap::CreateThreadPool() {
1012   const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
1013   if (num_threads != 0) {
1014     thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
1015   }
1016 }
1017 
MarkAllocStackAsLive(accounting::ObjectStack * stack)1018 void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
1019   space::ContinuousSpace* space1 = main_space_ != nullptr ? main_space_ : non_moving_space_;
1020   space::ContinuousSpace* space2 = non_moving_space_;
1021   // TODO: Generalize this to n bitmaps?
1022   CHECK(space1 != nullptr);
1023   CHECK(space2 != nullptr);
1024   MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
1025                  (large_object_space_ != nullptr ? large_object_space_->GetLiveBitmap() : nullptr),
1026                  stack);
1027 }
1028 
DeleteThreadPool()1029 void Heap::DeleteThreadPool() {
1030   thread_pool_.reset(nullptr);
1031 }
1032 
AddSpace(space::Space * space)1033 void Heap::AddSpace(space::Space* space) {
1034   CHECK(space != nullptr);
1035   WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1036   if (space->IsContinuousSpace()) {
1037     DCHECK(!space->IsDiscontinuousSpace());
1038     space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
1039     // Continuous spaces don't necessarily have bitmaps.
1040     accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
1041     accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
1042     // The region space bitmap is not added since VisitObjects visits the region space objects with
1043     // special handling.
1044     if (live_bitmap != nullptr && !space->IsRegionSpace()) {
1045       CHECK(mark_bitmap != nullptr);
1046       live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
1047       mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
1048     }
1049     continuous_spaces_.push_back(continuous_space);
1050     // Ensure that spaces remain sorted in increasing order of start address.
1051     std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
1052               [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
1053       return a->Begin() < b->Begin();
1054     });
1055   } else {
1056     CHECK(space->IsDiscontinuousSpace());
1057     space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
1058     live_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
1059     mark_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
1060     discontinuous_spaces_.push_back(discontinuous_space);
1061   }
1062   if (space->IsAllocSpace()) {
1063     alloc_spaces_.push_back(space->AsAllocSpace());
1064   }
1065 }
1066 
SetSpaceAsDefault(space::ContinuousSpace * continuous_space)1067 void Heap::SetSpaceAsDefault(space::ContinuousSpace* continuous_space) {
1068   WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1069   if (continuous_space->IsDlMallocSpace()) {
1070     dlmalloc_space_ = continuous_space->AsDlMallocSpace();
1071   } else if (continuous_space->IsRosAllocSpace()) {
1072     rosalloc_space_ = continuous_space->AsRosAllocSpace();
1073   }
1074 }
1075 
RemoveSpace(space::Space * space)1076 void Heap::RemoveSpace(space::Space* space) {
1077   DCHECK(space != nullptr);
1078   WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1079   if (space->IsContinuousSpace()) {
1080     DCHECK(!space->IsDiscontinuousSpace());
1081     space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
1082     // Continuous spaces don't necessarily have bitmaps.
1083     accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
1084     accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
1085     if (live_bitmap != nullptr && !space->IsRegionSpace()) {
1086       DCHECK(mark_bitmap != nullptr);
1087       live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
1088       mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
1089     }
1090     auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
1091     DCHECK(it != continuous_spaces_.end());
1092     continuous_spaces_.erase(it);
1093   } else {
1094     DCHECK(space->IsDiscontinuousSpace());
1095     space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
1096     live_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
1097     mark_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
1098     auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
1099                         discontinuous_space);
1100     DCHECK(it != discontinuous_spaces_.end());
1101     discontinuous_spaces_.erase(it);
1102   }
1103   if (space->IsAllocSpace()) {
1104     auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
1105     DCHECK(it != alloc_spaces_.end());
1106     alloc_spaces_.erase(it);
1107   }
1108 }
1109 
CalculateGcWeightedAllocatedBytes(uint64_t gc_last_process_cpu_time_ns,uint64_t current_process_cpu_time) const1110 double Heap::CalculateGcWeightedAllocatedBytes(uint64_t gc_last_process_cpu_time_ns,
1111                                                uint64_t current_process_cpu_time) const {
1112   uint64_t bytes_allocated = GetBytesAllocated();
1113   double weight = current_process_cpu_time - gc_last_process_cpu_time_ns;
1114   return weight * bytes_allocated;
1115 }
1116 
CalculatePreGcWeightedAllocatedBytes()1117 void Heap::CalculatePreGcWeightedAllocatedBytes() {
1118   uint64_t current_process_cpu_time = ProcessCpuNanoTime();
1119   pre_gc_weighted_allocated_bytes_ +=
1120     CalculateGcWeightedAllocatedBytes(pre_gc_last_process_cpu_time_ns_, current_process_cpu_time);
1121   pre_gc_last_process_cpu_time_ns_ = current_process_cpu_time;
1122 }
1123 
CalculatePostGcWeightedAllocatedBytes()1124 void Heap::CalculatePostGcWeightedAllocatedBytes() {
1125   uint64_t current_process_cpu_time = ProcessCpuNanoTime();
1126   post_gc_weighted_allocated_bytes_ +=
1127     CalculateGcWeightedAllocatedBytes(post_gc_last_process_cpu_time_ns_, current_process_cpu_time);
1128   post_gc_last_process_cpu_time_ns_ = current_process_cpu_time;
1129 }
1130 
GetTotalGcCpuTime()1131 uint64_t Heap::GetTotalGcCpuTime() {
1132   uint64_t sum = 0;
1133   for (auto* collector : garbage_collectors_) {
1134     sum += collector->GetTotalCpuTime();
1135   }
1136   return sum;
1137 }
1138 
DumpGcPerformanceInfo(std::ostream & os)1139 void Heap::DumpGcPerformanceInfo(std::ostream& os) {
1140   // Dump cumulative timings.
1141   os << "Dumping cumulative Gc timings\n";
1142   uint64_t total_duration = 0;
1143   // Dump cumulative loggers for each GC type.
1144   uint64_t total_paused_time = 0;
1145   for (auto* collector : garbage_collectors_) {
1146     total_duration += collector->GetCumulativeTimings().GetTotalNs();
1147     total_paused_time += collector->GetTotalPausedTimeNs();
1148     collector->DumpPerformanceInfo(os);
1149   }
1150   if (total_duration != 0) {
1151     const double total_seconds = total_duration / 1.0e9;
1152     const double total_cpu_seconds = GetTotalGcCpuTime() / 1.0e9;
1153     os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
1154     os << "Mean GC size throughput: "
1155        << PrettySize(GetBytesFreedEver() / total_seconds) << "/s"
1156        << " per cpu-time: "
1157        << PrettySize(GetBytesFreedEver() / total_cpu_seconds) << "/s\n";
1158     os << "Mean GC object throughput: "
1159        << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
1160   }
1161   uint64_t total_objects_allocated = GetObjectsAllocatedEver();
1162   os << "Total number of allocations " << total_objects_allocated << "\n";
1163   os << "Total bytes allocated " << PrettySize(GetBytesAllocatedEver()) << "\n";
1164   os << "Total bytes freed " << PrettySize(GetBytesFreedEver()) << "\n";
1165   os << "Free memory " << PrettySize(GetFreeMemory()) << "\n";
1166   os << "Free memory until GC " << PrettySize(GetFreeMemoryUntilGC()) << "\n";
1167   os << "Free memory until OOME " << PrettySize(GetFreeMemoryUntilOOME()) << "\n";
1168   os << "Total memory " << PrettySize(GetTotalMemory()) << "\n";
1169   os << "Max memory " << PrettySize(GetMaxMemory()) << "\n";
1170   if (HasZygoteSpace()) {
1171     os << "Zygote space size " << PrettySize(zygote_space_->Size()) << "\n";
1172   }
1173   os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
1174   os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
1175   os << "Total GC count: " << GetGcCount() << "\n";
1176   os << "Total GC time: " << PrettyDuration(GetGcTime()) << "\n";
1177   os << "Total blocking GC count: " << GetBlockingGcCount() << "\n";
1178   os << "Total blocking GC time: " << PrettyDuration(GetBlockingGcTime()) << "\n";
1179 
1180   {
1181     MutexLock mu(Thread::Current(), *gc_complete_lock_);
1182     if (gc_count_rate_histogram_.SampleSize() > 0U) {
1183       os << "Histogram of GC count per " << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
1184       gc_count_rate_histogram_.DumpBins(os);
1185       os << "\n";
1186     }
1187     if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1188       os << "Histogram of blocking GC count per "
1189          << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
1190       blocking_gc_count_rate_histogram_.DumpBins(os);
1191       os << "\n";
1192     }
1193   }
1194 
1195   if (kDumpRosAllocStatsOnSigQuit && rosalloc_space_ != nullptr) {
1196     rosalloc_space_->DumpStats(os);
1197   }
1198 
1199   os << "Native bytes total: " << GetNativeBytes()
1200      << " registered: " << native_bytes_registered_.load(std::memory_order_relaxed) << "\n";
1201 
1202   os << "Total native bytes at last GC: "
1203      << old_native_bytes_allocated_.load(std::memory_order_relaxed) << "\n";
1204 
1205   BaseMutex::DumpAll(os);
1206 }
1207 
ResetGcPerformanceInfo()1208 void Heap::ResetGcPerformanceInfo() {
1209   for (auto* collector : garbage_collectors_) {
1210     collector->ResetMeasurements();
1211   }
1212 
1213   process_cpu_start_time_ns_ = ProcessCpuNanoTime();
1214 
1215   pre_gc_last_process_cpu_time_ns_ = process_cpu_start_time_ns_;
1216   pre_gc_weighted_allocated_bytes_ = 0u;
1217 
1218   post_gc_last_process_cpu_time_ns_ = process_cpu_start_time_ns_;
1219   post_gc_weighted_allocated_bytes_ = 0u;
1220 
1221   total_bytes_freed_ever_.store(0);
1222   total_objects_freed_ever_.store(0);
1223   total_wait_time_ = 0;
1224   blocking_gc_count_ = 0;
1225   blocking_gc_time_ = 0;
1226   gc_count_last_window_ = 0;
1227   blocking_gc_count_last_window_ = 0;
1228   last_update_time_gc_count_rate_histograms_ =  // Round down by the window duration.
1229       (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
1230   {
1231     MutexLock mu(Thread::Current(), *gc_complete_lock_);
1232     gc_count_rate_histogram_.Reset();
1233     blocking_gc_count_rate_histogram_.Reset();
1234   }
1235 }
1236 
GetGcCount() const1237 uint64_t Heap::GetGcCount() const {
1238   uint64_t gc_count = 0U;
1239   for (auto* collector : garbage_collectors_) {
1240     gc_count += collector->GetCumulativeTimings().GetIterations();
1241   }
1242   return gc_count;
1243 }
1244 
GetGcTime() const1245 uint64_t Heap::GetGcTime() const {
1246   uint64_t gc_time = 0U;
1247   for (auto* collector : garbage_collectors_) {
1248     gc_time += collector->GetCumulativeTimings().GetTotalNs();
1249   }
1250   return gc_time;
1251 }
1252 
GetBlockingGcCount() const1253 uint64_t Heap::GetBlockingGcCount() const {
1254   return blocking_gc_count_;
1255 }
1256 
GetBlockingGcTime() const1257 uint64_t Heap::GetBlockingGcTime() const {
1258   return blocking_gc_time_;
1259 }
1260 
DumpGcCountRateHistogram(std::ostream & os) const1261 void Heap::DumpGcCountRateHistogram(std::ostream& os) const {
1262   MutexLock mu(Thread::Current(), *gc_complete_lock_);
1263   if (gc_count_rate_histogram_.SampleSize() > 0U) {
1264     gc_count_rate_histogram_.DumpBins(os);
1265   }
1266 }
1267 
DumpBlockingGcCountRateHistogram(std::ostream & os) const1268 void Heap::DumpBlockingGcCountRateHistogram(std::ostream& os) const {
1269   MutexLock mu(Thread::Current(), *gc_complete_lock_);
1270   if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1271     blocking_gc_count_rate_histogram_.DumpBins(os);
1272   }
1273 }
1274 
1275 ALWAYS_INLINE
GetAndOverwriteAllocationListener(Atomic<AllocationListener * > * storage,AllocationListener * new_value)1276 static inline AllocationListener* GetAndOverwriteAllocationListener(
1277     Atomic<AllocationListener*>* storage, AllocationListener* new_value) {
1278   return storage->exchange(new_value);
1279 }
1280 
~Heap()1281 Heap::~Heap() {
1282   VLOG(heap) << "Starting ~Heap()";
1283   STLDeleteElements(&garbage_collectors_);
1284   // If we don't reset then the mark stack complains in its destructor.
1285   allocation_stack_->Reset();
1286   allocation_records_.reset();
1287   live_stack_->Reset();
1288   STLDeleteValues(&mod_union_tables_);
1289   STLDeleteValues(&remembered_sets_);
1290   STLDeleteElements(&continuous_spaces_);
1291   STLDeleteElements(&discontinuous_spaces_);
1292   delete gc_complete_lock_;
1293   delete thread_flip_lock_;
1294   delete pending_task_lock_;
1295   delete backtrace_lock_;
1296   uint64_t unique_count = unique_backtrace_count_.load();
1297   uint64_t seen_count = seen_backtrace_count_.load();
1298   if (unique_count != 0 || seen_count != 0) {
1299     LOG(INFO) << "gc stress unique=" << unique_count << " total=" << (unique_count + seen_count);
1300   }
1301   VLOG(heap) << "Finished ~Heap()";
1302 }
1303 
1304 
FindContinuousSpaceFromAddress(const mirror::Object * addr) const1305 space::ContinuousSpace* Heap::FindContinuousSpaceFromAddress(const mirror::Object* addr) const {
1306   for (const auto& space : continuous_spaces_) {
1307     if (space->Contains(addr)) {
1308       return space;
1309     }
1310   }
1311   return nullptr;
1312 }
1313 
FindContinuousSpaceFromObject(ObjPtr<mirror::Object> obj,bool fail_ok) const1314 space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(ObjPtr<mirror::Object> obj,
1315                                                             bool fail_ok) const {
1316   space::ContinuousSpace* space = FindContinuousSpaceFromAddress(obj.Ptr());
1317   if (space != nullptr) {
1318     return space;
1319   }
1320   if (!fail_ok) {
1321     LOG(FATAL) << "object " << obj << " not inside any spaces!";
1322   }
1323   return nullptr;
1324 }
1325 
FindDiscontinuousSpaceFromObject(ObjPtr<mirror::Object> obj,bool fail_ok) const1326 space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(ObjPtr<mirror::Object> obj,
1327                                                                   bool fail_ok) const {
1328   for (const auto& space : discontinuous_spaces_) {
1329     if (space->Contains(obj.Ptr())) {
1330       return space;
1331     }
1332   }
1333   if (!fail_ok) {
1334     LOG(FATAL) << "object " << obj << " not inside any spaces!";
1335   }
1336   return nullptr;
1337 }
1338 
FindSpaceFromObject(ObjPtr<mirror::Object> obj,bool fail_ok) const1339 space::Space* Heap::FindSpaceFromObject(ObjPtr<mirror::Object> obj, bool fail_ok) const {
1340   space::Space* result = FindContinuousSpaceFromObject(obj, true);
1341   if (result != nullptr) {
1342     return result;
1343   }
1344   return FindDiscontinuousSpaceFromObject(obj, fail_ok);
1345 }
1346 
FindSpaceFromAddress(const void * addr) const1347 space::Space* Heap::FindSpaceFromAddress(const void* addr) const {
1348   for (const auto& space : continuous_spaces_) {
1349     if (space->Contains(reinterpret_cast<const mirror::Object*>(addr))) {
1350       return space;
1351     }
1352   }
1353   for (const auto& space : discontinuous_spaces_) {
1354     if (space->Contains(reinterpret_cast<const mirror::Object*>(addr))) {
1355       return space;
1356     }
1357   }
1358   return nullptr;
1359 }
1360 
DumpSpaceNameFromAddress(const void * addr) const1361 std::string Heap::DumpSpaceNameFromAddress(const void* addr) const {
1362   space::Space* space = FindSpaceFromAddress(addr);
1363   return (space != nullptr) ? space->GetName() : "no space";
1364 }
1365 
ThrowOutOfMemoryError(Thread * self,size_t byte_count,AllocatorType allocator_type)1366 void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, AllocatorType allocator_type) {
1367   // If we're in a stack overflow, do not create a new exception. It would require running the
1368   // constructor, which will of course still be in a stack overflow.
1369   if (self->IsHandlingStackOverflow()) {
1370     self->SetException(
1371         Runtime::Current()->GetPreAllocatedOutOfMemoryErrorWhenHandlingStackOverflow());
1372     return;
1373   }
1374 
1375   std::ostringstream oss;
1376   size_t total_bytes_free = GetFreeMemory();
1377   oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
1378       << " free bytes and " << PrettySize(GetFreeMemoryUntilOOME()) << " until OOM,"
1379       << " target footprint " << target_footprint_.load(std::memory_order_relaxed)
1380       << ", growth limit "
1381       << growth_limit_;
1382   // If the allocation failed due to fragmentation, print out the largest continuous allocation.
1383   if (total_bytes_free >= byte_count) {
1384     space::AllocSpace* space = nullptr;
1385     if (allocator_type == kAllocatorTypeNonMoving) {
1386       space = non_moving_space_;
1387     } else if (allocator_type == kAllocatorTypeRosAlloc ||
1388                allocator_type == kAllocatorTypeDlMalloc) {
1389       space = main_space_;
1390     } else if (allocator_type == kAllocatorTypeBumpPointer ||
1391                allocator_type == kAllocatorTypeTLAB) {
1392       space = bump_pointer_space_;
1393     } else if (allocator_type == kAllocatorTypeRegion ||
1394                allocator_type == kAllocatorTypeRegionTLAB) {
1395       space = region_space_;
1396     }
1397     if (space != nullptr) {
1398       space->LogFragmentationAllocFailure(oss, byte_count);
1399     }
1400   }
1401   self->ThrowOutOfMemoryError(oss.str().c_str());
1402 }
1403 
DoPendingCollectorTransition()1404 void Heap::DoPendingCollectorTransition() {
1405   CollectorType desired_collector_type = desired_collector_type_;
1406   // Launch homogeneous space compaction if it is desired.
1407   if (desired_collector_type == kCollectorTypeHomogeneousSpaceCompact) {
1408     if (!CareAboutPauseTimes()) {
1409       PerformHomogeneousSpaceCompact();
1410     } else {
1411       VLOG(gc) << "Homogeneous compaction ignored due to jank perceptible process state";
1412     }
1413   } else if (desired_collector_type == kCollectorTypeCCBackground) {
1414     DCHECK(kUseReadBarrier);
1415     if (!CareAboutPauseTimes()) {
1416       // Invoke CC full compaction.
1417       CollectGarbageInternal(collector::kGcTypeFull,
1418                              kGcCauseCollectorTransition,
1419                              /*clear_soft_references=*/false);
1420     } else {
1421       VLOG(gc) << "CC background compaction ignored due to jank perceptible process state";
1422     }
1423   } else {
1424     CHECK_EQ(desired_collector_type, collector_type_) << "Unsupported collector transition";
1425   }
1426 }
1427 
Trim(Thread * self)1428 void Heap::Trim(Thread* self) {
1429   Runtime* const runtime = Runtime::Current();
1430   if (!CareAboutPauseTimes()) {
1431     // Deflate the monitors, this can cause a pause but shouldn't matter since we don't care
1432     // about pauses.
1433     ScopedTrace trace("Deflating monitors");
1434     // Avoid race conditions on the lock word for CC.
1435     ScopedGCCriticalSection gcs(self, kGcCauseTrim, kCollectorTypeHeapTrim);
1436     ScopedSuspendAll ssa(__FUNCTION__);
1437     uint64_t start_time = NanoTime();
1438     size_t count = runtime->GetMonitorList()->DeflateMonitors();
1439     VLOG(heap) << "Deflating " << count << " monitors took "
1440         << PrettyDuration(NanoTime() - start_time);
1441   }
1442   TrimIndirectReferenceTables(self);
1443   TrimSpaces(self);
1444   // Trim arenas that may have been used by JIT or verifier.
1445   runtime->GetArenaPool()->TrimMaps();
1446 }
1447 
1448 class TrimIndirectReferenceTableClosure : public Closure {
1449  public:
TrimIndirectReferenceTableClosure(Barrier * barrier)1450   explicit TrimIndirectReferenceTableClosure(Barrier* barrier) : barrier_(barrier) {
1451   }
Run(Thread * thread)1452   void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
1453     thread->GetJniEnv()->TrimLocals();
1454     // If thread is a running mutator, then act on behalf of the trim thread.
1455     // See the code in ThreadList::RunCheckpoint.
1456     barrier_->Pass(Thread::Current());
1457   }
1458 
1459  private:
1460   Barrier* const barrier_;
1461 };
1462 
TrimIndirectReferenceTables(Thread * self)1463 void Heap::TrimIndirectReferenceTables(Thread* self) {
1464   ScopedObjectAccess soa(self);
1465   ScopedTrace trace(__PRETTY_FUNCTION__);
1466   JavaVMExt* vm = soa.Vm();
1467   // Trim globals indirect reference table.
1468   vm->TrimGlobals();
1469   // Trim locals indirect reference tables.
1470   Barrier barrier(0);
1471   TrimIndirectReferenceTableClosure closure(&barrier);
1472   ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1473   size_t barrier_count = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1474   if (barrier_count != 0) {
1475     barrier.Increment(self, barrier_count);
1476   }
1477 }
1478 
StartGC(Thread * self,GcCause cause,CollectorType collector_type)1479 void Heap::StartGC(Thread* self, GcCause cause, CollectorType collector_type) {
1480   // Need to do this before acquiring the locks since we don't want to get suspended while
1481   // holding any locks.
1482   ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1483   MutexLock mu(self, *gc_complete_lock_);
1484   // Ensure there is only one GC at a time.
1485   WaitForGcToCompleteLocked(cause, self);
1486   collector_type_running_ = collector_type;
1487   last_gc_cause_ = cause;
1488   thread_running_gc_ = self;
1489 }
1490 
TrimSpaces(Thread * self)1491 void Heap::TrimSpaces(Thread* self) {
1492   // Pretend we are doing a GC to prevent background compaction from deleting the space we are
1493   // trimming.
1494   StartGC(self, kGcCauseTrim, kCollectorTypeHeapTrim);
1495   ScopedTrace trace(__PRETTY_FUNCTION__);
1496   const uint64_t start_ns = NanoTime();
1497   // Trim the managed spaces.
1498   uint64_t total_alloc_space_allocated = 0;
1499   uint64_t total_alloc_space_size = 0;
1500   uint64_t managed_reclaimed = 0;
1501   {
1502     ScopedObjectAccess soa(self);
1503     for (const auto& space : continuous_spaces_) {
1504       if (space->IsMallocSpace()) {
1505         gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
1506         if (malloc_space->IsRosAllocSpace() || !CareAboutPauseTimes()) {
1507           // Don't trim dlmalloc spaces if we care about pauses since this can hold the space lock
1508           // for a long period of time.
1509           managed_reclaimed += malloc_space->Trim();
1510         }
1511         total_alloc_space_size += malloc_space->Size();
1512       }
1513     }
1514   }
1515   total_alloc_space_allocated = GetBytesAllocated();
1516   if (large_object_space_ != nullptr) {
1517     total_alloc_space_allocated -= large_object_space_->GetBytesAllocated();
1518   }
1519   if (bump_pointer_space_ != nullptr) {
1520     total_alloc_space_allocated -= bump_pointer_space_->Size();
1521   }
1522   if (region_space_ != nullptr) {
1523     total_alloc_space_allocated -= region_space_->GetBytesAllocated();
1524   }
1525   const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
1526       static_cast<float>(total_alloc_space_size);
1527   uint64_t gc_heap_end_ns = NanoTime();
1528   // We never move things in the native heap, so we can finish the GC at this point.
1529   FinishGC(self, collector::kGcTypeNone);
1530 
1531   VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
1532       << ", advised=" << PrettySize(managed_reclaimed) << ") heap. Managed heap utilization of "
1533       << static_cast<int>(100 * managed_utilization) << "%.";
1534 }
1535 
IsValidObjectAddress(const void * addr) const1536 bool Heap::IsValidObjectAddress(const void* addr) const {
1537   if (addr == nullptr) {
1538     return true;
1539   }
1540   return IsAligned<kObjectAlignment>(addr) && FindSpaceFromAddress(addr) != nullptr;
1541 }
1542 
IsNonDiscontinuousSpaceHeapAddress(const void * addr) const1543 bool Heap::IsNonDiscontinuousSpaceHeapAddress(const void* addr) const {
1544   return FindContinuousSpaceFromAddress(reinterpret_cast<const mirror::Object*>(addr)) != nullptr;
1545 }
1546 
IsLiveObjectLocked(ObjPtr<mirror::Object> obj,bool search_allocation_stack,bool search_live_stack,bool sorted)1547 bool Heap::IsLiveObjectLocked(ObjPtr<mirror::Object> obj,
1548                               bool search_allocation_stack,
1549                               bool search_live_stack,
1550                               bool sorted) {
1551   if (UNLIKELY(!IsAligned<kObjectAlignment>(obj.Ptr()))) {
1552     return false;
1553   }
1554   if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj.Ptr())) {
1555     mirror::Class* klass = obj->GetClass<kVerifyNone>();
1556     if (obj == klass) {
1557       // This case happens for java.lang.Class.
1558       return true;
1559     }
1560     return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
1561   } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj.Ptr())) {
1562     // If we are in the allocated region of the temp space, then we are probably live (e.g. during
1563     // a GC). When a GC isn't running End() - Begin() is 0 which means no objects are contained.
1564     return temp_space_->Contains(obj.Ptr());
1565   }
1566   if (region_space_ != nullptr && region_space_->HasAddress(obj.Ptr())) {
1567     return true;
1568   }
1569   space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
1570   space::DiscontinuousSpace* d_space = nullptr;
1571   if (c_space != nullptr) {
1572     if (c_space->GetLiveBitmap()->Test(obj.Ptr())) {
1573       return true;
1574     }
1575   } else {
1576     d_space = FindDiscontinuousSpaceFromObject(obj, true);
1577     if (d_space != nullptr) {
1578       if (d_space->GetLiveBitmap()->Test(obj.Ptr())) {
1579         return true;
1580       }
1581     }
1582   }
1583   // This is covering the allocation/live stack swapping that is done without mutators suspended.
1584   for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
1585     if (i > 0) {
1586       NanoSleep(MsToNs(10));
1587     }
1588     if (search_allocation_stack) {
1589       if (sorted) {
1590         if (allocation_stack_->ContainsSorted(obj.Ptr())) {
1591           return true;
1592         }
1593       } else if (allocation_stack_->Contains(obj.Ptr())) {
1594         return true;
1595       }
1596     }
1597 
1598     if (search_live_stack) {
1599       if (sorted) {
1600         if (live_stack_->ContainsSorted(obj.Ptr())) {
1601           return true;
1602         }
1603       } else if (live_stack_->Contains(obj.Ptr())) {
1604         return true;
1605       }
1606     }
1607   }
1608   // We need to check the bitmaps again since there is a race where we mark something as live and
1609   // then clear the stack containing it.
1610   if (c_space != nullptr) {
1611     if (c_space->GetLiveBitmap()->Test(obj.Ptr())) {
1612       return true;
1613     }
1614   } else {
1615     d_space = FindDiscontinuousSpaceFromObject(obj, true);
1616     if (d_space != nullptr && d_space->GetLiveBitmap()->Test(obj.Ptr())) {
1617       return true;
1618     }
1619   }
1620   return false;
1621 }
1622 
DumpSpaces() const1623 std::string Heap::DumpSpaces() const {
1624   std::ostringstream oss;
1625   DumpSpaces(oss);
1626   return oss.str();
1627 }
1628 
DumpSpaces(std::ostream & stream) const1629 void Heap::DumpSpaces(std::ostream& stream) const {
1630   for (const auto& space : continuous_spaces_) {
1631     accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1632     accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1633     stream << space << " " << *space << "\n";
1634     if (live_bitmap != nullptr) {
1635       stream << live_bitmap << " " << *live_bitmap << "\n";
1636     }
1637     if (mark_bitmap != nullptr) {
1638       stream << mark_bitmap << " " << *mark_bitmap << "\n";
1639     }
1640   }
1641   for (const auto& space : discontinuous_spaces_) {
1642     stream << space << " " << *space << "\n";
1643   }
1644 }
1645 
VerifyObjectBody(ObjPtr<mirror::Object> obj)1646 void Heap::VerifyObjectBody(ObjPtr<mirror::Object> obj) {
1647   if (verify_object_mode_ == kVerifyObjectModeDisabled) {
1648     return;
1649   }
1650 
1651   // Ignore early dawn of the universe verifications.
1652   if (UNLIKELY(num_bytes_allocated_.load(std::memory_order_relaxed) < 10 * KB)) {
1653     return;
1654   }
1655   CHECK_ALIGNED(obj.Ptr(), kObjectAlignment) << "Object isn't aligned";
1656   mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(mirror::Object::ClassOffset());
1657   CHECK(c != nullptr) << "Null class in object " << obj;
1658   CHECK_ALIGNED(c, kObjectAlignment) << "Class " << c << " not aligned in object " << obj;
1659   CHECK(VerifyClassClass(c));
1660 
1661   if (verify_object_mode_ > kVerifyObjectModeFast) {
1662     // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
1663     CHECK(IsLiveObjectLocked(obj)) << "Object is dead " << obj << "\n" << DumpSpaces();
1664   }
1665 }
1666 
VerifyHeap()1667 void Heap::VerifyHeap() {
1668   ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1669   auto visitor = [&](mirror::Object* obj) {
1670     VerifyObjectBody(obj);
1671   };
1672   // Technically we need the mutator lock here to call Visit. However, VerifyObjectBody is already
1673   // NO_THREAD_SAFETY_ANALYSIS.
1674   auto no_thread_safety_analysis = [&]() NO_THREAD_SAFETY_ANALYSIS {
1675     GetLiveBitmap()->Visit(visitor);
1676   };
1677   no_thread_safety_analysis();
1678 }
1679 
RecordFree(uint64_t freed_objects,int64_t freed_bytes)1680 void Heap::RecordFree(uint64_t freed_objects, int64_t freed_bytes) {
1681   // Use signed comparison since freed bytes can be negative when background compaction foreground
1682   // transitions occurs. This is typically due to objects moving from a bump pointer space to a
1683   // free list backed space, which may increase memory footprint due to padding and binning.
1684   RACING_DCHECK_LE(freed_bytes,
1685                    static_cast<int64_t>(num_bytes_allocated_.load(std::memory_order_relaxed)));
1686   // Note: This relies on 2s complement for handling negative freed_bytes.
1687   num_bytes_allocated_.fetch_sub(static_cast<ssize_t>(freed_bytes), std::memory_order_relaxed);
1688   if (Runtime::Current()->HasStatsEnabled()) {
1689     RuntimeStats* thread_stats = Thread::Current()->GetStats();
1690     thread_stats->freed_objects += freed_objects;
1691     thread_stats->freed_bytes += freed_bytes;
1692     // TODO: Do this concurrently.
1693     RuntimeStats* global_stats = Runtime::Current()->GetStats();
1694     global_stats->freed_objects += freed_objects;
1695     global_stats->freed_bytes += freed_bytes;
1696   }
1697 }
1698 
RecordFreeRevoke()1699 void Heap::RecordFreeRevoke() {
1700   // Subtract num_bytes_freed_revoke_ from num_bytes_allocated_ to cancel out the
1701   // ahead-of-time, bulk counting of bytes allocated in rosalloc thread-local buffers.
1702   // If there's a concurrent revoke, ok to not necessarily reset num_bytes_freed_revoke_
1703   // all the way to zero exactly as the remainder will be subtracted at the next GC.
1704   size_t bytes_freed = num_bytes_freed_revoke_.load(std::memory_order_relaxed);
1705   CHECK_GE(num_bytes_freed_revoke_.fetch_sub(bytes_freed, std::memory_order_relaxed),
1706            bytes_freed) << "num_bytes_freed_revoke_ underflow";
1707   CHECK_GE(num_bytes_allocated_.fetch_sub(bytes_freed, std::memory_order_relaxed),
1708            bytes_freed) << "num_bytes_allocated_ underflow";
1709   GetCurrentGcIteration()->SetFreedRevoke(bytes_freed);
1710 }
1711 
GetRosAllocSpace(gc::allocator::RosAlloc * rosalloc) const1712 space::RosAllocSpace* Heap::GetRosAllocSpace(gc::allocator::RosAlloc* rosalloc) const {
1713   if (rosalloc_space_ != nullptr && rosalloc_space_->GetRosAlloc() == rosalloc) {
1714     return rosalloc_space_;
1715   }
1716   for (const auto& space : continuous_spaces_) {
1717     if (space->AsContinuousSpace()->IsRosAllocSpace()) {
1718       if (space->AsContinuousSpace()->AsRosAllocSpace()->GetRosAlloc() == rosalloc) {
1719         return space->AsContinuousSpace()->AsRosAllocSpace();
1720       }
1721     }
1722   }
1723   return nullptr;
1724 }
1725 
EntrypointsInstrumented()1726 static inline bool EntrypointsInstrumented() REQUIRES_SHARED(Locks::mutator_lock_) {
1727   instrumentation::Instrumentation* const instrumentation =
1728       Runtime::Current()->GetInstrumentation();
1729   return instrumentation != nullptr && instrumentation->AllocEntrypointsInstrumented();
1730 }
1731 
AllocateInternalWithGc(Thread * self,AllocatorType allocator,bool instrumented,size_t alloc_size,size_t * bytes_allocated,size_t * usable_size,size_t * bytes_tl_bulk_allocated,ObjPtr<mirror::Class> * klass)1732 mirror::Object* Heap::AllocateInternalWithGc(Thread* self,
1733                                              AllocatorType allocator,
1734                                              bool instrumented,
1735                                              size_t alloc_size,
1736                                              size_t* bytes_allocated,
1737                                              size_t* usable_size,
1738                                              size_t* bytes_tl_bulk_allocated,
1739                                              ObjPtr<mirror::Class>* klass) {
1740   bool was_default_allocator = allocator == GetCurrentAllocator();
1741   // Make sure there is no pending exception since we may need to throw an OOME.
1742   self->AssertNoPendingException();
1743   DCHECK(klass != nullptr);
1744 
1745   StackHandleScope<1> hs(self);
1746   HandleWrapperObjPtr<mirror::Class> h_klass(hs.NewHandleWrapper(klass));
1747 
1748   auto send_object_pre_alloc =
1749       [&]() REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_) {
1750         if (UNLIKELY(instrumented)) {
1751           AllocationListener* l = alloc_listener_.load(std::memory_order_seq_cst);
1752           if (UNLIKELY(l != nullptr) && UNLIKELY(l->HasPreAlloc())) {
1753             l->PreObjectAllocated(self, h_klass, &alloc_size);
1754           }
1755         }
1756       };
1757 #define PERFORM_SUSPENDING_OPERATION(op)                                          \
1758   [&]() REQUIRES(Roles::uninterruptible_) REQUIRES_SHARED(Locks::mutator_lock_) { \
1759     ScopedAllowThreadSuspension ats;                                              \
1760     auto res = (op);                                                              \
1761     send_object_pre_alloc();                                                      \
1762     return res;                                                                   \
1763   }()
1764 
1765   // The allocation failed. If the GC is running, block until it completes, and then retry the
1766   // allocation.
1767   collector::GcType last_gc =
1768       PERFORM_SUSPENDING_OPERATION(WaitForGcToComplete(kGcCauseForAlloc, self));
1769   // If we were the default allocator but the allocator changed while we were suspended,
1770   // abort the allocation.
1771   if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1772       (!instrumented && EntrypointsInstrumented())) {
1773     return nullptr;
1774   }
1775   if (last_gc != collector::kGcTypeNone) {
1776     // A GC was in progress and we blocked, retry allocation now that memory has been freed.
1777     mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
1778                                                      usable_size, bytes_tl_bulk_allocated);
1779     if (ptr != nullptr) {
1780       return ptr;
1781     }
1782   }
1783 
1784   collector::GcType tried_type = next_gc_type_;
1785   const bool gc_ran = PERFORM_SUSPENDING_OPERATION(
1786       CollectGarbageInternal(tried_type, kGcCauseForAlloc, false) != collector::kGcTypeNone);
1787 
1788   if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1789       (!instrumented && EntrypointsInstrumented())) {
1790     return nullptr;
1791   }
1792   if (gc_ran) {
1793     mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
1794                                                      usable_size, bytes_tl_bulk_allocated);
1795     if (ptr != nullptr) {
1796       return ptr;
1797     }
1798   }
1799 
1800   // Loop through our different Gc types and try to Gc until we get enough free memory.
1801   for (collector::GcType gc_type : gc_plan_) {
1802     if (gc_type == tried_type) {
1803       continue;
1804     }
1805     // Attempt to run the collector, if we succeed, re-try the allocation.
1806     const bool plan_gc_ran = PERFORM_SUSPENDING_OPERATION(
1807         CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone);
1808     if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1809         (!instrumented && EntrypointsInstrumented())) {
1810       return nullptr;
1811     }
1812     if (plan_gc_ran) {
1813       // Did we free sufficient memory for the allocation to succeed?
1814       mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
1815                                                        usable_size, bytes_tl_bulk_allocated);
1816       if (ptr != nullptr) {
1817         return ptr;
1818       }
1819     }
1820   }
1821   // Allocations have failed after GCs;  this is an exceptional state.
1822   // Try harder, growing the heap if necessary.
1823   mirror::Object* ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
1824                                                   usable_size, bytes_tl_bulk_allocated);
1825   if (ptr != nullptr) {
1826     return ptr;
1827   }
1828   // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1829   // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1830   // VM spec requires that all SoftReferences have been collected and cleared before throwing
1831   // OOME.
1832   VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1833            << " allocation";
1834   // TODO: Run finalization, but this may cause more allocations to occur.
1835   // We don't need a WaitForGcToComplete here either.
1836   DCHECK(!gc_plan_.empty());
1837   PERFORM_SUSPENDING_OPERATION(CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true));
1838   if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1839       (!instrumented && EntrypointsInstrumented())) {
1840     return nullptr;
1841   }
1842   ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size,
1843                                   bytes_tl_bulk_allocated);
1844   if (ptr == nullptr) {
1845     const uint64_t current_time = NanoTime();
1846     switch (allocator) {
1847       case kAllocatorTypeRosAlloc:
1848         // Fall-through.
1849       case kAllocatorTypeDlMalloc: {
1850         if (use_homogeneous_space_compaction_for_oom_ &&
1851             current_time - last_time_homogeneous_space_compaction_by_oom_ >
1852             min_interval_homogeneous_space_compaction_by_oom_) {
1853           last_time_homogeneous_space_compaction_by_oom_ = current_time;
1854           HomogeneousSpaceCompactResult result =
1855               PERFORM_SUSPENDING_OPERATION(PerformHomogeneousSpaceCompact());
1856           // Thread suspension could have occurred.
1857           if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1858               (!instrumented && EntrypointsInstrumented())) {
1859             return nullptr;
1860           }
1861           switch (result) {
1862             case HomogeneousSpaceCompactResult::kSuccess:
1863               // If the allocation succeeded, we delayed an oom.
1864               ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
1865                                               usable_size, bytes_tl_bulk_allocated);
1866               if (ptr != nullptr) {
1867                 count_delayed_oom_++;
1868               }
1869               break;
1870             case HomogeneousSpaceCompactResult::kErrorReject:
1871               // Reject due to disabled moving GC.
1872               break;
1873             case HomogeneousSpaceCompactResult::kErrorVMShuttingDown:
1874               // Throw OOM by default.
1875               break;
1876             default: {
1877               UNIMPLEMENTED(FATAL) << "homogeneous space compaction result: "
1878                   << static_cast<size_t>(result);
1879               UNREACHABLE();
1880             }
1881           }
1882           // Always print that we ran homogeneous space compation since this can cause jank.
1883           VLOG(heap) << "Ran heap homogeneous space compaction, "
1884                     << " requested defragmentation "
1885                     << count_requested_homogeneous_space_compaction_.load()
1886                     << " performed defragmentation "
1887                     << count_performed_homogeneous_space_compaction_.load()
1888                     << " ignored homogeneous space compaction "
1889                     << count_ignored_homogeneous_space_compaction_.load()
1890                     << " delayed count = "
1891                     << count_delayed_oom_.load();
1892         }
1893         break;
1894       }
1895       default: {
1896         // Do nothing for others allocators.
1897       }
1898     }
1899   }
1900 #undef PERFORM_SUSPENDING_OPERATION
1901   // If the allocation hasn't succeeded by this point, throw an OOM error.
1902   if (ptr == nullptr) {
1903     ScopedAllowThreadSuspension ats;
1904     ThrowOutOfMemoryError(self, alloc_size, allocator);
1905   }
1906   return ptr;
1907 }
1908 
SetTargetHeapUtilization(float target)1909 void Heap::SetTargetHeapUtilization(float target) {
1910   DCHECK_GT(target, 0.1f);  // asserted in Java code
1911   DCHECK_LT(target, 1.0f);
1912   target_utilization_ = target;
1913 }
1914 
GetObjectsAllocated() const1915 size_t Heap::GetObjectsAllocated() const {
1916   Thread* const self = Thread::Current();
1917   ScopedThreadStateChange tsc(self, kWaitingForGetObjectsAllocated);
1918   // Prevent GC running during GetObjectsAllocated since we may get a checkpoint request that tells
1919   // us to suspend while we are doing SuspendAll. b/35232978
1920   gc::ScopedGCCriticalSection gcs(Thread::Current(),
1921                                   gc::kGcCauseGetObjectsAllocated,
1922                                   gc::kCollectorTypeGetObjectsAllocated);
1923   // Need SuspendAll here to prevent lock violation if RosAlloc does it during InspectAll.
1924   ScopedSuspendAll ssa(__FUNCTION__);
1925   ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1926   size_t total = 0;
1927   for (space::AllocSpace* space : alloc_spaces_) {
1928     total += space->GetObjectsAllocated();
1929   }
1930   return total;
1931 }
1932 
GetObjectsAllocatedEver() const1933 uint64_t Heap::GetObjectsAllocatedEver() const {
1934   uint64_t total = GetObjectsFreedEver();
1935   // If we are detached, we can't use GetObjectsAllocated since we can't change thread states.
1936   if (Thread::Current() != nullptr) {
1937     total += GetObjectsAllocated();
1938   }
1939   return total;
1940 }
1941 
GetBytesAllocatedEver() const1942 uint64_t Heap::GetBytesAllocatedEver() const {
1943   // Force the returned value to be monotonically increasing, in the sense that if this is called
1944   // at A and B, such that A happens-before B, then the call at B returns a value no smaller than
1945   // that at A. This is not otherwise guaranteed, since num_bytes_allocated_ is decremented first,
1946   // and total_bytes_freed_ever_ is incremented later.
1947   static std::atomic<uint64_t> max_bytes_so_far(0);
1948   uint64_t so_far = max_bytes_so_far.load(std::memory_order_relaxed);
1949   uint64_t current_bytes = GetBytesFreedEver(std::memory_order_acquire);
1950   current_bytes += GetBytesAllocated();
1951   do {
1952     if (current_bytes <= so_far) {
1953       return so_far;
1954     }
1955   } while (!max_bytes_so_far.compare_exchange_weak(so_far /* updated */,
1956                                                    current_bytes, std::memory_order_relaxed));
1957   return current_bytes;
1958 }
1959 
1960 // Check whether the given object is an instance of the given class.
MatchesClass(mirror::Object * obj,Handle<mirror::Class> h_class,bool use_is_assignable_from)1961 static bool MatchesClass(mirror::Object* obj,
1962                          Handle<mirror::Class> h_class,
1963                          bool use_is_assignable_from) REQUIRES_SHARED(Locks::mutator_lock_) {
1964   mirror::Class* instance_class = obj->GetClass();
1965   CHECK(instance_class != nullptr);
1966   ObjPtr<mirror::Class> klass = h_class.Get();
1967   if (use_is_assignable_from) {
1968     return klass != nullptr && klass->IsAssignableFrom(instance_class);
1969   }
1970   return instance_class == klass;
1971 }
1972 
CountInstances(const std::vector<Handle<mirror::Class>> & classes,bool use_is_assignable_from,uint64_t * counts)1973 void Heap::CountInstances(const std::vector<Handle<mirror::Class>>& classes,
1974                           bool use_is_assignable_from,
1975                           uint64_t* counts) {
1976   auto instance_counter = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1977     for (size_t i = 0; i < classes.size(); ++i) {
1978       if (MatchesClass(obj, classes[i], use_is_assignable_from)) {
1979         ++counts[i];
1980       }
1981     }
1982   };
1983   VisitObjects(instance_counter);
1984 }
1985 
GetInstances(VariableSizedHandleScope & scope,Handle<mirror::Class> h_class,bool use_is_assignable_from,int32_t max_count,std::vector<Handle<mirror::Object>> & instances)1986 void Heap::GetInstances(VariableSizedHandleScope& scope,
1987                         Handle<mirror::Class> h_class,
1988                         bool use_is_assignable_from,
1989                         int32_t max_count,
1990                         std::vector<Handle<mirror::Object>>& instances) {
1991   DCHECK_GE(max_count, 0);
1992   auto instance_collector = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1993     if (MatchesClass(obj, h_class, use_is_assignable_from)) {
1994       if (max_count == 0 || instances.size() < static_cast<size_t>(max_count)) {
1995         instances.push_back(scope.NewHandle(obj));
1996       }
1997     }
1998   };
1999   VisitObjects(instance_collector);
2000 }
2001 
GetReferringObjects(VariableSizedHandleScope & scope,Handle<mirror::Object> o,int32_t max_count,std::vector<Handle<mirror::Object>> & referring_objects)2002 void Heap::GetReferringObjects(VariableSizedHandleScope& scope,
2003                                Handle<mirror::Object> o,
2004                                int32_t max_count,
2005                                std::vector<Handle<mirror::Object>>& referring_objects) {
2006   class ReferringObjectsFinder {
2007    public:
2008     ReferringObjectsFinder(VariableSizedHandleScope& scope_in,
2009                            Handle<mirror::Object> object_in,
2010                            int32_t max_count_in,
2011                            std::vector<Handle<mirror::Object>>& referring_objects_in)
2012         REQUIRES_SHARED(Locks::mutator_lock_)
2013         : scope_(scope_in),
2014           object_(object_in),
2015           max_count_(max_count_in),
2016           referring_objects_(referring_objects_in) {}
2017 
2018     // For Object::VisitReferences.
2019     void operator()(ObjPtr<mirror::Object> obj,
2020                     MemberOffset offset,
2021                     bool is_static ATTRIBUTE_UNUSED) const
2022         REQUIRES_SHARED(Locks::mutator_lock_) {
2023       mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
2024       if (ref == object_.Get() && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
2025         referring_objects_.push_back(scope_.NewHandle(obj));
2026       }
2027     }
2028 
2029     void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
2030         const {}
2031     void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
2032 
2033    private:
2034     VariableSizedHandleScope& scope_;
2035     Handle<mirror::Object> const object_;
2036     const uint32_t max_count_;
2037     std::vector<Handle<mirror::Object>>& referring_objects_;
2038     DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
2039   };
2040   ReferringObjectsFinder finder(scope, o, max_count, referring_objects);
2041   auto referring_objects_finder = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2042     obj->VisitReferences(finder, VoidFunctor());
2043   };
2044   VisitObjects(referring_objects_finder);
2045 }
2046 
CollectGarbage(bool clear_soft_references,GcCause cause)2047 void Heap::CollectGarbage(bool clear_soft_references, GcCause cause) {
2048   // Even if we waited for a GC we still need to do another GC since weaks allocated during the
2049   // last GC will not have necessarily been cleared.
2050   CollectGarbageInternal(gc_plan_.back(), cause, clear_soft_references);
2051 }
2052 
SupportHomogeneousSpaceCompactAndCollectorTransitions() const2053 bool Heap::SupportHomogeneousSpaceCompactAndCollectorTransitions() const {
2054   return main_space_backup_.get() != nullptr && main_space_ != nullptr &&
2055       foreground_collector_type_ == kCollectorTypeCMS;
2056 }
2057 
PerformHomogeneousSpaceCompact()2058 HomogeneousSpaceCompactResult Heap::PerformHomogeneousSpaceCompact() {
2059   Thread* self = Thread::Current();
2060   // Inc requested homogeneous space compaction.
2061   count_requested_homogeneous_space_compaction_++;
2062   // Store performed homogeneous space compaction at a new request arrival.
2063   ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
2064   Locks::mutator_lock_->AssertNotHeld(self);
2065   {
2066     ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
2067     MutexLock mu(self, *gc_complete_lock_);
2068     // Ensure there is only one GC at a time.
2069     WaitForGcToCompleteLocked(kGcCauseHomogeneousSpaceCompact, self);
2070     // Homogeneous space compaction is a copying transition, can't run it if the moving GC disable
2071     // count is non zero.
2072     // If the collector type changed to something which doesn't benefit from homogeneous space
2073     // compaction, exit.
2074     if (disable_moving_gc_count_ != 0 || IsMovingGc(collector_type_) ||
2075         !main_space_->CanMoveObjects()) {
2076       return kErrorReject;
2077     }
2078     if (!SupportHomogeneousSpaceCompactAndCollectorTransitions()) {
2079       return kErrorUnsupported;
2080     }
2081     collector_type_running_ = kCollectorTypeHomogeneousSpaceCompact;
2082   }
2083   if (Runtime::Current()->IsShuttingDown(self)) {
2084     // Don't allow heap transitions to happen if the runtime is shutting down since these can
2085     // cause objects to get finalized.
2086     FinishGC(self, collector::kGcTypeNone);
2087     return HomogeneousSpaceCompactResult::kErrorVMShuttingDown;
2088   }
2089   collector::GarbageCollector* collector;
2090   {
2091     ScopedSuspendAll ssa(__FUNCTION__);
2092     uint64_t start_time = NanoTime();
2093     // Launch compaction.
2094     space::MallocSpace* to_space = main_space_backup_.release();
2095     space::MallocSpace* from_space = main_space_;
2096     to_space->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2097     const uint64_t space_size_before_compaction = from_space->Size();
2098     AddSpace(to_space);
2099     // Make sure that we will have enough room to copy.
2100     CHECK_GE(to_space->GetFootprintLimit(), from_space->GetFootprintLimit());
2101     collector = Compact(to_space, from_space, kGcCauseHomogeneousSpaceCompact);
2102     const uint64_t space_size_after_compaction = to_space->Size();
2103     main_space_ = to_space;
2104     main_space_backup_.reset(from_space);
2105     RemoveSpace(from_space);
2106     SetSpaceAsDefault(main_space_);  // Set as default to reset the proper dlmalloc space.
2107     // Update performed homogeneous space compaction count.
2108     count_performed_homogeneous_space_compaction_++;
2109     // Print statics log and resume all threads.
2110     uint64_t duration = NanoTime() - start_time;
2111     VLOG(heap) << "Heap homogeneous space compaction took " << PrettyDuration(duration) << " size: "
2112                << PrettySize(space_size_before_compaction) << " -> "
2113                << PrettySize(space_size_after_compaction) << " compact-ratio: "
2114                << std::fixed << static_cast<double>(space_size_after_compaction) /
2115                static_cast<double>(space_size_before_compaction);
2116   }
2117   // Finish GC.
2118   // Get the references we need to enqueue.
2119   SelfDeletingTask* clear = reference_processor_->CollectClearedReferences(self);
2120   GrowForUtilization(semi_space_collector_);
2121   LogGC(kGcCauseHomogeneousSpaceCompact, collector);
2122   FinishGC(self, collector::kGcTypeFull);
2123   // Enqueue any references after losing the GC locks.
2124   clear->Run(self);
2125   clear->Finalize();
2126   {
2127     ScopedObjectAccess soa(self);
2128     soa.Vm()->UnloadNativeLibraries();
2129   }
2130   return HomogeneousSpaceCompactResult::kSuccess;
2131 }
2132 
ChangeCollector(CollectorType collector_type)2133 void Heap::ChangeCollector(CollectorType collector_type) {
2134   // TODO: Only do this with all mutators suspended to avoid races.
2135   if (collector_type != collector_type_) {
2136     collector_type_ = collector_type;
2137     gc_plan_.clear();
2138     switch (collector_type_) {
2139       case kCollectorTypeCC: {
2140         if (use_generational_cc_) {
2141           gc_plan_.push_back(collector::kGcTypeSticky);
2142         }
2143         gc_plan_.push_back(collector::kGcTypeFull);
2144         if (use_tlab_) {
2145           ChangeAllocator(kAllocatorTypeRegionTLAB);
2146         } else {
2147           ChangeAllocator(kAllocatorTypeRegion);
2148         }
2149         break;
2150       }
2151       case kCollectorTypeSS: {
2152         gc_plan_.push_back(collector::kGcTypeFull);
2153         if (use_tlab_) {
2154           ChangeAllocator(kAllocatorTypeTLAB);
2155         } else {
2156           ChangeAllocator(kAllocatorTypeBumpPointer);
2157         }
2158         break;
2159       }
2160       case kCollectorTypeMS: {
2161         gc_plan_.push_back(collector::kGcTypeSticky);
2162         gc_plan_.push_back(collector::kGcTypePartial);
2163         gc_plan_.push_back(collector::kGcTypeFull);
2164         ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
2165         break;
2166       }
2167       case kCollectorTypeCMS: {
2168         gc_plan_.push_back(collector::kGcTypeSticky);
2169         gc_plan_.push_back(collector::kGcTypePartial);
2170         gc_plan_.push_back(collector::kGcTypeFull);
2171         ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
2172         break;
2173       }
2174       default: {
2175         UNIMPLEMENTED(FATAL);
2176         UNREACHABLE();
2177       }
2178     }
2179     if (IsGcConcurrent()) {
2180       concurrent_start_bytes_ =
2181           UnsignedDifference(target_footprint_.load(std::memory_order_relaxed),
2182                              kMinConcurrentRemainingBytes);
2183     } else {
2184       concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
2185     }
2186   }
2187 }
2188 
2189 // Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
2190 class ZygoteCompactingCollector final : public collector::SemiSpace {
2191  public:
ZygoteCompactingCollector(gc::Heap * heap,bool is_running_on_memory_tool)2192   ZygoteCompactingCollector(gc::Heap* heap, bool is_running_on_memory_tool)
2193       : SemiSpace(heap, "zygote collector"),
2194         bin_live_bitmap_(nullptr),
2195         bin_mark_bitmap_(nullptr),
2196         is_running_on_memory_tool_(is_running_on_memory_tool) {}
2197 
BuildBins(space::ContinuousSpace * space)2198   void BuildBins(space::ContinuousSpace* space) REQUIRES_SHARED(Locks::mutator_lock_) {
2199     bin_live_bitmap_ = space->GetLiveBitmap();
2200     bin_mark_bitmap_ = space->GetMarkBitmap();
2201     uintptr_t prev = reinterpret_cast<uintptr_t>(space->Begin());
2202     WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2203     // Note: This requires traversing the space in increasing order of object addresses.
2204     auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2205       uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
2206       size_t bin_size = object_addr - prev;
2207       // Add the bin consisting of the end of the previous object to the start of the current object.
2208       AddBin(bin_size, prev);
2209       prev = object_addr + RoundUp(obj->SizeOf<kDefaultVerifyFlags>(), kObjectAlignment);
2210     };
2211     bin_live_bitmap_->Walk(visitor);
2212     // Add the last bin which spans after the last object to the end of the space.
2213     AddBin(reinterpret_cast<uintptr_t>(space->End()) - prev, prev);
2214   }
2215 
2216  private:
2217   // Maps from bin sizes to locations.
2218   std::multimap<size_t, uintptr_t> bins_;
2219   // Live bitmap of the space which contains the bins.
2220   accounting::ContinuousSpaceBitmap* bin_live_bitmap_;
2221   // Mark bitmap of the space which contains the bins.
2222   accounting::ContinuousSpaceBitmap* bin_mark_bitmap_;
2223   const bool is_running_on_memory_tool_;
2224 
AddBin(size_t size,uintptr_t position)2225   void AddBin(size_t size, uintptr_t position) {
2226     if (is_running_on_memory_tool_) {
2227       MEMORY_TOOL_MAKE_DEFINED(reinterpret_cast<void*>(position), size);
2228     }
2229     if (size != 0) {
2230       bins_.insert(std::make_pair(size, position));
2231     }
2232   }
2233 
ShouldSweepSpace(space::ContinuousSpace * space ATTRIBUTE_UNUSED) const2234   bool ShouldSweepSpace(space::ContinuousSpace* space ATTRIBUTE_UNUSED) const override {
2235     // Don't sweep any spaces since we probably blasted the internal accounting of the free list
2236     // allocator.
2237     return false;
2238   }
2239 
MarkNonForwardedObject(mirror::Object * obj)2240   mirror::Object* MarkNonForwardedObject(mirror::Object* obj) override
2241       REQUIRES(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
2242     size_t obj_size = obj->SizeOf<kDefaultVerifyFlags>();
2243     size_t alloc_size = RoundUp(obj_size, kObjectAlignment);
2244     mirror::Object* forward_address;
2245     // Find the smallest bin which we can move obj in.
2246     auto it = bins_.lower_bound(alloc_size);
2247     if (it == bins_.end()) {
2248       // No available space in the bins, place it in the target space instead (grows the zygote
2249       // space).
2250       size_t bytes_allocated, dummy;
2251       forward_address = to_space_->Alloc(self_, alloc_size, &bytes_allocated, nullptr, &dummy);
2252       if (to_space_live_bitmap_ != nullptr) {
2253         to_space_live_bitmap_->Set(forward_address);
2254       } else {
2255         GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
2256         GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
2257       }
2258     } else {
2259       size_t size = it->first;
2260       uintptr_t pos = it->second;
2261       bins_.erase(it);  // Erase the old bin which we replace with the new smaller bin.
2262       forward_address = reinterpret_cast<mirror::Object*>(pos);
2263       // Set the live and mark bits so that sweeping system weaks works properly.
2264       bin_live_bitmap_->Set(forward_address);
2265       bin_mark_bitmap_->Set(forward_address);
2266       DCHECK_GE(size, alloc_size);
2267       // Add a new bin with the remaining space.
2268       AddBin(size - alloc_size, pos + alloc_size);
2269     }
2270     // Copy the object over to its new location.
2271     // Historical note: We did not use `alloc_size` to avoid a Valgrind error.
2272     memcpy(reinterpret_cast<void*>(forward_address), obj, obj_size);
2273     if (kUseBakerReadBarrier) {
2274       obj->AssertReadBarrierState();
2275       forward_address->AssertReadBarrierState();
2276     }
2277     return forward_address;
2278   }
2279 };
2280 
UnBindBitmaps()2281 void Heap::UnBindBitmaps() {
2282   TimingLogger::ScopedTiming t("UnBindBitmaps", GetCurrentGcIteration()->GetTimings());
2283   for (const auto& space : GetContinuousSpaces()) {
2284     if (space->IsContinuousMemMapAllocSpace()) {
2285       space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
2286       if (alloc_space->GetLiveBitmap() != nullptr && alloc_space->HasBoundBitmaps()) {
2287         alloc_space->UnBindBitmaps();
2288       }
2289     }
2290   }
2291 }
2292 
IncrementFreedEver()2293 void Heap::IncrementFreedEver() {
2294   // Counters are updated only by us, but may be read concurrently.
2295   // The updates should become visible after the corresponding live object info.
2296   total_objects_freed_ever_.store(total_objects_freed_ever_.load(std::memory_order_relaxed)
2297                                   + GetCurrentGcIteration()->GetFreedObjects()
2298                                   + GetCurrentGcIteration()->GetFreedLargeObjects(),
2299                                   std::memory_order_release);
2300   total_bytes_freed_ever_.store(total_bytes_freed_ever_.load(std::memory_order_relaxed)
2301                                 + GetCurrentGcIteration()->GetFreedBytes()
2302                                 + GetCurrentGcIteration()->GetFreedLargeObjectBytes(),
2303                                 std::memory_order_release);
2304 }
2305 
2306 #pragma clang diagnostic push
2307 #if !ART_USE_FUTEXES
2308 // Frame gets too large, perhaps due to Bionic pthread_mutex_lock size. We don't care.
2309 #  pragma clang diagnostic ignored "-Wframe-larger-than="
2310 #endif
2311 // This has a large frame, but shouldn't be run anywhere near the stack limit.
PreZygoteFork()2312 void Heap::PreZygoteFork() {
2313   if (!HasZygoteSpace()) {
2314     // We still want to GC in case there is some unreachable non moving objects that could cause a
2315     // suboptimal bin packing when we compact the zygote space.
2316     CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
2317     // Trim the pages at the end of the non moving space. Trim while not holding zygote lock since
2318     // the trim process may require locking the mutator lock.
2319     non_moving_space_->Trim();
2320   }
2321   Thread* self = Thread::Current();
2322   MutexLock mu(self, zygote_creation_lock_);
2323   // Try to see if we have any Zygote spaces.
2324   if (HasZygoteSpace()) {
2325     return;
2326   }
2327   Runtime::Current()->GetInternTable()->AddNewTable();
2328   Runtime::Current()->GetClassLinker()->MoveClassTableToPreZygote();
2329   VLOG(heap) << "Starting PreZygoteFork";
2330   // The end of the non-moving space may be protected, unprotect it so that we can copy the zygote
2331   // there.
2332   non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2333   const bool same_space = non_moving_space_ == main_space_;
2334   if (kCompactZygote) {
2335     // Temporarily disable rosalloc verification because the zygote
2336     // compaction will mess up the rosalloc internal metadata.
2337     ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
2338     ZygoteCompactingCollector zygote_collector(this, is_running_on_memory_tool_);
2339     zygote_collector.BuildBins(non_moving_space_);
2340     // Create a new bump pointer space which we will compact into.
2341     space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
2342                                          non_moving_space_->Limit());
2343     // Compact the bump pointer space to a new zygote bump pointer space.
2344     bool reset_main_space = false;
2345     if (IsMovingGc(collector_type_)) {
2346       if (collector_type_ == kCollectorTypeCC) {
2347         zygote_collector.SetFromSpace(region_space_);
2348       } else {
2349         zygote_collector.SetFromSpace(bump_pointer_space_);
2350       }
2351     } else {
2352       CHECK(main_space_ != nullptr);
2353       CHECK_NE(main_space_, non_moving_space_)
2354           << "Does not make sense to compact within the same space";
2355       // Copy from the main space.
2356       zygote_collector.SetFromSpace(main_space_);
2357       reset_main_space = true;
2358     }
2359     zygote_collector.SetToSpace(&target_space);
2360     zygote_collector.SetSwapSemiSpaces(false);
2361     zygote_collector.Run(kGcCauseCollectorTransition, false);
2362     if (reset_main_space) {
2363       main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2364       madvise(main_space_->Begin(), main_space_->Capacity(), MADV_DONTNEED);
2365       MemMap mem_map = main_space_->ReleaseMemMap();
2366       RemoveSpace(main_space_);
2367       space::Space* old_main_space = main_space_;
2368       CreateMainMallocSpace(std::move(mem_map),
2369                             kDefaultInitialSize,
2370                             std::min(mem_map.Size(), growth_limit_),
2371                             mem_map.Size());
2372       delete old_main_space;
2373       AddSpace(main_space_);
2374     } else {
2375       if (collector_type_ == kCollectorTypeCC) {
2376         region_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2377         // Evacuated everything out of the region space, clear the mark bitmap.
2378         region_space_->GetMarkBitmap()->Clear();
2379       } else {
2380         bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2381       }
2382     }
2383     if (temp_space_ != nullptr) {
2384       CHECK(temp_space_->IsEmpty());
2385     }
2386     IncrementFreedEver();
2387     // Update the end and write out image.
2388     non_moving_space_->SetEnd(target_space.End());
2389     non_moving_space_->SetLimit(target_space.Limit());
2390     VLOG(heap) << "Create zygote space with size=" << non_moving_space_->Size() << " bytes";
2391   }
2392   // Change the collector to the post zygote one.
2393   ChangeCollector(foreground_collector_type_);
2394   // Save the old space so that we can remove it after we complete creating the zygote space.
2395   space::MallocSpace* old_alloc_space = non_moving_space_;
2396   // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
2397   // the remaining available space.
2398   // Remove the old space before creating the zygote space since creating the zygote space sets
2399   // the old alloc space's bitmaps to null.
2400   RemoveSpace(old_alloc_space);
2401   if (collector::SemiSpace::kUseRememberedSet) {
2402     // Sanity bound check.
2403     FindRememberedSetFromSpace(old_alloc_space)->AssertAllDirtyCardsAreWithinSpace();
2404     // Remove the remembered set for the now zygote space (the old
2405     // non-moving space). Note now that we have compacted objects into
2406     // the zygote space, the data in the remembered set is no longer
2407     // needed. The zygote space will instead have a mod-union table
2408     // from this point on.
2409     RemoveRememberedSet(old_alloc_space);
2410   }
2411   // Remaining space becomes the new non moving space.
2412   zygote_space_ = old_alloc_space->CreateZygoteSpace(kNonMovingSpaceName, low_memory_mode_,
2413                                                      &non_moving_space_);
2414   CHECK(!non_moving_space_->CanMoveObjects());
2415   if (same_space) {
2416     main_space_ = non_moving_space_;
2417     SetSpaceAsDefault(main_space_);
2418   }
2419   delete old_alloc_space;
2420   CHECK(HasZygoteSpace()) << "Failed creating zygote space";
2421   AddSpace(zygote_space_);
2422   non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
2423   AddSpace(non_moving_space_);
2424   constexpr bool set_mark_bit = kUseBakerReadBarrier
2425                                 && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects;
2426   if (set_mark_bit) {
2427     // Treat all of the objects in the zygote as marked to avoid unnecessary dirty pages. This is
2428     // safe since we mark all of the objects that may reference non immune objects as gray.
2429     zygote_space_->SetMarkBitInLiveObjects();
2430   }
2431 
2432   // Create the zygote space mod union table.
2433   accounting::ModUnionTable* mod_union_table =
2434       new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space_);
2435   CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
2436 
2437   if (collector_type_ != kCollectorTypeCC) {
2438     // Set all the cards in the mod-union table since we don't know which objects contain references
2439     // to large objects.
2440     mod_union_table->SetCards();
2441   } else {
2442     // Make sure to clear the zygote space cards so that we don't dirty pages in the next GC. There
2443     // may be dirty cards from the zygote compaction or reference processing. These cards are not
2444     // necessary to have marked since the zygote space may not refer to any objects not in the
2445     // zygote or image spaces at this point.
2446     mod_union_table->ProcessCards();
2447     mod_union_table->ClearTable();
2448 
2449     // For CC we never collect zygote large objects. This means we do not need to set the cards for
2450     // the zygote mod-union table and we can also clear all of the existing image mod-union tables.
2451     // The existing mod-union tables are only for image spaces and may only reference zygote and
2452     // image objects.
2453     for (auto& pair : mod_union_tables_) {
2454       CHECK(pair.first->IsImageSpace());
2455       CHECK(!pair.first->AsImageSpace()->GetImageHeader().IsAppImage());
2456       accounting::ModUnionTable* table = pair.second;
2457       table->ClearTable();
2458     }
2459   }
2460   AddModUnionTable(mod_union_table);
2461   large_object_space_->SetAllLargeObjectsAsZygoteObjects(self, set_mark_bit);
2462   if (collector::SemiSpace::kUseRememberedSet) {
2463     // Add a new remembered set for the post-zygote non-moving space.
2464     accounting::RememberedSet* post_zygote_non_moving_space_rem_set =
2465         new accounting::RememberedSet("Post-zygote non-moving space remembered set", this,
2466                                       non_moving_space_);
2467     CHECK(post_zygote_non_moving_space_rem_set != nullptr)
2468         << "Failed to create post-zygote non-moving space remembered set";
2469     AddRememberedSet(post_zygote_non_moving_space_rem_set);
2470   }
2471 }
2472 #pragma clang diagnostic pop
2473 
FlushAllocStack()2474 void Heap::FlushAllocStack() {
2475   MarkAllocStackAsLive(allocation_stack_.get());
2476   allocation_stack_->Reset();
2477 }
2478 
MarkAllocStack(accounting::ContinuousSpaceBitmap * bitmap1,accounting::ContinuousSpaceBitmap * bitmap2,accounting::LargeObjectBitmap * large_objects,accounting::ObjectStack * stack)2479 void Heap::MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1,
2480                           accounting::ContinuousSpaceBitmap* bitmap2,
2481                           accounting::LargeObjectBitmap* large_objects,
2482                           accounting::ObjectStack* stack) {
2483   DCHECK(bitmap1 != nullptr);
2484   DCHECK(bitmap2 != nullptr);
2485   const auto* limit = stack->End();
2486   for (auto* it = stack->Begin(); it != limit; ++it) {
2487     const mirror::Object* obj = it->AsMirrorPtr();
2488     if (!kUseThreadLocalAllocationStack || obj != nullptr) {
2489       if (bitmap1->HasAddress(obj)) {
2490         bitmap1->Set(obj);
2491       } else if (bitmap2->HasAddress(obj)) {
2492         bitmap2->Set(obj);
2493       } else {
2494         DCHECK(large_objects != nullptr);
2495         large_objects->Set(obj);
2496       }
2497     }
2498   }
2499 }
2500 
SwapSemiSpaces()2501 void Heap::SwapSemiSpaces() {
2502   CHECK(bump_pointer_space_ != nullptr);
2503   CHECK(temp_space_ != nullptr);
2504   std::swap(bump_pointer_space_, temp_space_);
2505 }
2506 
Compact(space::ContinuousMemMapAllocSpace * target_space,space::ContinuousMemMapAllocSpace * source_space,GcCause gc_cause)2507 collector::GarbageCollector* Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
2508                                            space::ContinuousMemMapAllocSpace* source_space,
2509                                            GcCause gc_cause) {
2510   CHECK(kMovingCollector);
2511   if (target_space != source_space) {
2512     // Don't swap spaces since this isn't a typical semi space collection.
2513     semi_space_collector_->SetSwapSemiSpaces(false);
2514     semi_space_collector_->SetFromSpace(source_space);
2515     semi_space_collector_->SetToSpace(target_space);
2516     semi_space_collector_->Run(gc_cause, false);
2517     return semi_space_collector_;
2518   }
2519   LOG(FATAL) << "Unsupported";
2520   UNREACHABLE();
2521 }
2522 
TraceHeapSize(size_t heap_size)2523 void Heap::TraceHeapSize(size_t heap_size) {
2524   ATraceIntegerValue("Heap size (KB)", heap_size / KB);
2525 }
2526 
2527 #if defined(__GLIBC__)
2528 # define IF_GLIBC(x) x
2529 #else
2530 # define IF_GLIBC(x)
2531 #endif
2532 
GetNativeBytes()2533 size_t Heap::GetNativeBytes() {
2534   size_t malloc_bytes;
2535 #if defined(__BIONIC__) || defined(__GLIBC__)
2536   IF_GLIBC(size_t mmapped_bytes;)
2537   struct mallinfo mi = mallinfo();
2538   // In spite of the documentation, the jemalloc version of this call seems to do what we want,
2539   // and it is thread-safe.
2540   if (sizeof(size_t) > sizeof(mi.uordblks) && sizeof(size_t) > sizeof(mi.hblkhd)) {
2541     // Shouldn't happen, but glibc declares uordblks as int.
2542     // Avoiding sign extension gets us correct behavior for another 2 GB.
2543     malloc_bytes = (unsigned int)mi.uordblks;
2544     IF_GLIBC(mmapped_bytes = (unsigned int)mi.hblkhd;)
2545   } else {
2546     malloc_bytes = mi.uordblks;
2547     IF_GLIBC(mmapped_bytes = mi.hblkhd;)
2548   }
2549   // From the spec, it appeared mmapped_bytes <= malloc_bytes. Reality was sometimes
2550   // dramatically different. (b/119580449 was an early bug.) If so, we try to fudge it.
2551   // However, malloc implementations seem to interpret hblkhd differently, namely as
2552   // mapped blocks backing the entire heap (e.g. jemalloc) vs. large objects directly
2553   // allocated via mmap (e.g. glibc). Thus we now only do this for glibc, where it
2554   // previously helped, and which appears to use a reading of the spec compatible
2555   // with our adjustment.
2556 #if defined(__GLIBC__)
2557   if (mmapped_bytes > malloc_bytes) {
2558     malloc_bytes = mmapped_bytes;
2559   }
2560 #endif  // GLIBC
2561 #else  // Neither Bionic nor Glibc
2562   // We should hit this case only in contexts in which GC triggering is not critical. Effectively
2563   // disable GC triggering based on malloc().
2564   malloc_bytes = 1000;
2565 #endif
2566   return malloc_bytes + native_bytes_registered_.load(std::memory_order_relaxed);
2567   // An alternative would be to get RSS from /proc/self/statm. Empirically, that's no
2568   // more expensive, and it would allow us to count memory allocated by means other than malloc.
2569   // However it would change as pages are unmapped and remapped due to memory pressure, among
2570   // other things. It seems risky to trigger GCs as a result of such changes.
2571 }
2572 
CollectGarbageInternal(collector::GcType gc_type,GcCause gc_cause,bool clear_soft_references)2573 collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type,
2574                                                GcCause gc_cause,
2575                                                bool clear_soft_references) {
2576   Thread* self = Thread::Current();
2577   Runtime* runtime = Runtime::Current();
2578   // If the heap can't run the GC, silently fail and return that no GC was run.
2579   switch (gc_type) {
2580     case collector::kGcTypePartial: {
2581       if (!HasZygoteSpace()) {
2582         return collector::kGcTypeNone;
2583       }
2584       break;
2585     }
2586     default: {
2587       // Other GC types don't have any special cases which makes them not runnable. The main case
2588       // here is full GC.
2589     }
2590   }
2591   ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
2592   Locks::mutator_lock_->AssertNotHeld(self);
2593   if (self->IsHandlingStackOverflow()) {
2594     // If we are throwing a stack overflow error we probably don't have enough remaining stack
2595     // space to run the GC.
2596     return collector::kGcTypeNone;
2597   }
2598   bool compacting_gc;
2599   {
2600     gc_complete_lock_->AssertNotHeld(self);
2601     ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
2602     MutexLock mu(self, *gc_complete_lock_);
2603     // Ensure there is only one GC at a time.
2604     WaitForGcToCompleteLocked(gc_cause, self);
2605     compacting_gc = IsMovingGc(collector_type_);
2606     // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
2607     if (compacting_gc && disable_moving_gc_count_ != 0) {
2608       LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
2609       return collector::kGcTypeNone;
2610     }
2611     if (gc_disabled_for_shutdown_) {
2612       return collector::kGcTypeNone;
2613     }
2614     collector_type_running_ = collector_type_;
2615   }
2616   if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
2617     ++runtime->GetStats()->gc_for_alloc_count;
2618     ++self->GetStats()->gc_for_alloc_count;
2619   }
2620   const size_t bytes_allocated_before_gc = GetBytesAllocated();
2621 
2622   DCHECK_LT(gc_type, collector::kGcTypeMax);
2623   DCHECK_NE(gc_type, collector::kGcTypeNone);
2624 
2625   collector::GarbageCollector* collector = nullptr;
2626   // TODO: Clean this up.
2627   if (compacting_gc) {
2628     DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
2629            current_allocator_ == kAllocatorTypeTLAB ||
2630            current_allocator_ == kAllocatorTypeRegion ||
2631            current_allocator_ == kAllocatorTypeRegionTLAB);
2632     switch (collector_type_) {
2633       case kCollectorTypeSS:
2634         semi_space_collector_->SetFromSpace(bump_pointer_space_);
2635         semi_space_collector_->SetToSpace(temp_space_);
2636         semi_space_collector_->SetSwapSemiSpaces(true);
2637         collector = semi_space_collector_;
2638         break;
2639       case kCollectorTypeCC:
2640         if (use_generational_cc_) {
2641           // TODO: Other threads must do the flip checkpoint before they start poking at
2642           // active_concurrent_copying_collector_. So we should not concurrency here.
2643           active_concurrent_copying_collector_ = (gc_type == collector::kGcTypeSticky) ?
2644               young_concurrent_copying_collector_ : concurrent_copying_collector_;
2645           DCHECK(active_concurrent_copying_collector_->RegionSpace() == region_space_);
2646         }
2647         collector = active_concurrent_copying_collector_;
2648         break;
2649       default:
2650         LOG(FATAL) << "Invalid collector type " << static_cast<size_t>(collector_type_);
2651     }
2652     if (collector != active_concurrent_copying_collector_) {
2653       temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2654       if (kIsDebugBuild) {
2655         // Try to read each page of the memory map in case mprotect didn't work properly b/19894268.
2656         temp_space_->GetMemMap()->TryReadable();
2657       }
2658       CHECK(temp_space_->IsEmpty());
2659     }
2660     gc_type = collector::kGcTypeFull;  // TODO: Not hard code this in.
2661   } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
2662       current_allocator_ == kAllocatorTypeDlMalloc) {
2663     collector = FindCollectorByGcType(gc_type);
2664   } else {
2665     LOG(FATAL) << "Invalid current allocator " << current_allocator_;
2666   }
2667 
2668   CHECK(collector != nullptr)
2669       << "Could not find garbage collector with collector_type="
2670       << static_cast<size_t>(collector_type_) << " and gc_type=" << gc_type;
2671   collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
2672   IncrementFreedEver();
2673   RequestTrim(self);
2674   // Collect cleared references.
2675   SelfDeletingTask* clear = reference_processor_->CollectClearedReferences(self);
2676   // Grow the heap so that we know when to perform the next GC.
2677   GrowForUtilization(collector, bytes_allocated_before_gc);
2678   LogGC(gc_cause, collector);
2679   FinishGC(self, gc_type);
2680   // Actually enqueue all cleared references. Do this after the GC has officially finished since
2681   // otherwise we can deadlock.
2682   clear->Run(self);
2683   clear->Finalize();
2684   // Inform DDMS that a GC completed.
2685   Dbg::GcDidFinish();
2686 
2687   old_native_bytes_allocated_.store(GetNativeBytes());
2688 
2689   // Unload native libraries for class unloading. We do this after calling FinishGC to prevent
2690   // deadlocks in case the JNI_OnUnload function does allocations.
2691   {
2692     ScopedObjectAccess soa(self);
2693     soa.Vm()->UnloadNativeLibraries();
2694   }
2695   return gc_type;
2696 }
2697 
LogGC(GcCause gc_cause,collector::GarbageCollector * collector)2698 void Heap::LogGC(GcCause gc_cause, collector::GarbageCollector* collector) {
2699   const size_t duration = GetCurrentGcIteration()->GetDurationNs();
2700   const std::vector<uint64_t>& pause_times = GetCurrentGcIteration()->GetPauseTimes();
2701   // Print the GC if it is an explicit GC (e.g. Runtime.gc()) or a slow GC
2702   // (mutator time blocked >= long_pause_log_threshold_).
2703   bool log_gc = kLogAllGCs || gc_cause == kGcCauseExplicit;
2704   if (!log_gc && CareAboutPauseTimes()) {
2705     // GC for alloc pauses the allocating thread, so consider it as a pause.
2706     log_gc = duration > long_gc_log_threshold_ ||
2707         (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
2708     for (uint64_t pause : pause_times) {
2709       log_gc = log_gc || pause >= long_pause_log_threshold_;
2710     }
2711   }
2712   if (log_gc) {
2713     const size_t percent_free = GetPercentFree();
2714     const size_t current_heap_size = GetBytesAllocated();
2715     const size_t total_memory = GetTotalMemory();
2716     std::ostringstream pause_string;
2717     for (size_t i = 0; i < pause_times.size(); ++i) {
2718       pause_string << PrettyDuration((pause_times[i] / 1000) * 1000)
2719                    << ((i != pause_times.size() - 1) ? "," : "");
2720     }
2721     LOG(INFO) << gc_cause << " " << collector->GetName()
2722               << " GC freed "  << current_gc_iteration_.GetFreedObjects() << "("
2723               << PrettySize(current_gc_iteration_.GetFreedBytes()) << ") AllocSpace objects, "
2724               << current_gc_iteration_.GetFreedLargeObjects() << "("
2725               << PrettySize(current_gc_iteration_.GetFreedLargeObjectBytes()) << ") LOS objects, "
2726               << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
2727               << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
2728               << " total " << PrettyDuration((duration / 1000) * 1000);
2729     VLOG(heap) << Dumpable<TimingLogger>(*current_gc_iteration_.GetTimings());
2730   }
2731 }
2732 
FinishGC(Thread * self,collector::GcType gc_type)2733 void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
2734   MutexLock mu(self, *gc_complete_lock_);
2735   collector_type_running_ = kCollectorTypeNone;
2736   if (gc_type != collector::kGcTypeNone) {
2737     last_gc_type_ = gc_type;
2738 
2739     // Update stats.
2740     ++gc_count_last_window_;
2741     if (running_collection_is_blocking_) {
2742       // If the currently running collection was a blocking one,
2743       // increment the counters and reset the flag.
2744       ++blocking_gc_count_;
2745       blocking_gc_time_ += GetCurrentGcIteration()->GetDurationNs();
2746       ++blocking_gc_count_last_window_;
2747     }
2748     // Update the gc count rate histograms if due.
2749     UpdateGcCountRateHistograms();
2750   }
2751   // Reset.
2752   running_collection_is_blocking_ = false;
2753   thread_running_gc_ = nullptr;
2754   // Wake anyone who may have been waiting for the GC to complete.
2755   gc_complete_cond_->Broadcast(self);
2756 }
2757 
UpdateGcCountRateHistograms()2758 void Heap::UpdateGcCountRateHistograms() {
2759   // Invariant: if the time since the last update includes more than
2760   // one windows, all the GC runs (if > 0) must have happened in first
2761   // window because otherwise the update must have already taken place
2762   // at an earlier GC run. So, we report the non-first windows with
2763   // zero counts to the histograms.
2764   DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2765   uint64_t now = NanoTime();
2766   DCHECK_GE(now, last_update_time_gc_count_rate_histograms_);
2767   uint64_t time_since_last_update = now - last_update_time_gc_count_rate_histograms_;
2768   uint64_t num_of_windows = time_since_last_update / kGcCountRateHistogramWindowDuration;
2769 
2770   // The computed number of windows can be incoherently high if NanoTime() is not monotonic.
2771   // Setting a limit on its maximum value reduces the impact on CPU time in such cases.
2772   if (num_of_windows > kGcCountRateHistogramMaxNumMissedWindows) {
2773     LOG(WARNING) << "Reducing the number of considered missed Gc histogram windows from "
2774                  << num_of_windows << " to " << kGcCountRateHistogramMaxNumMissedWindows;
2775     num_of_windows = kGcCountRateHistogramMaxNumMissedWindows;
2776   }
2777 
2778   if (time_since_last_update >= kGcCountRateHistogramWindowDuration) {
2779     // Record the first window.
2780     gc_count_rate_histogram_.AddValue(gc_count_last_window_ - 1);  // Exclude the current run.
2781     blocking_gc_count_rate_histogram_.AddValue(running_collection_is_blocking_ ?
2782         blocking_gc_count_last_window_ - 1 : blocking_gc_count_last_window_);
2783     // Record the other windows (with zero counts).
2784     for (uint64_t i = 0; i < num_of_windows - 1; ++i) {
2785       gc_count_rate_histogram_.AddValue(0);
2786       blocking_gc_count_rate_histogram_.AddValue(0);
2787     }
2788     // Update the last update time and reset the counters.
2789     last_update_time_gc_count_rate_histograms_ =
2790         (now / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
2791     gc_count_last_window_ = 1;  // Include the current run.
2792     blocking_gc_count_last_window_ = running_collection_is_blocking_ ? 1 : 0;
2793   }
2794   DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2795 }
2796 
2797 class RootMatchesObjectVisitor : public SingleRootVisitor {
2798  public:
RootMatchesObjectVisitor(const mirror::Object * obj)2799   explicit RootMatchesObjectVisitor(const mirror::Object* obj) : obj_(obj) { }
2800 
VisitRoot(mirror::Object * root,const RootInfo & info)2801   void VisitRoot(mirror::Object* root, const RootInfo& info)
2802       override REQUIRES_SHARED(Locks::mutator_lock_) {
2803     if (root == obj_) {
2804       LOG(INFO) << "Object " << obj_ << " is a root " << info.ToString();
2805     }
2806   }
2807 
2808  private:
2809   const mirror::Object* const obj_;
2810 };
2811 
2812 
2813 class ScanVisitor {
2814  public:
operator ()(const mirror::Object * obj) const2815   void operator()(const mirror::Object* obj) const {
2816     LOG(ERROR) << "Would have rescanned object " << obj;
2817   }
2818 };
2819 
2820 // Verify a reference from an object.
2821 class VerifyReferenceVisitor : public SingleRootVisitor {
2822  public:
VerifyReferenceVisitor(Thread * self,Heap * heap,size_t * fail_count,bool verify_referent)2823   VerifyReferenceVisitor(Thread* self, Heap* heap, size_t* fail_count, bool verify_referent)
2824       REQUIRES_SHARED(Locks::mutator_lock_)
2825       : self_(self), heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {
2826     CHECK_EQ(self_, Thread::Current());
2827   }
2828 
operator ()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,ObjPtr<mirror::Reference> ref) const2829   void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED, ObjPtr<mirror::Reference> ref) const
2830       REQUIRES_SHARED(Locks::mutator_lock_) {
2831     if (verify_referent_) {
2832       VerifyReference(ref.Ptr(), ref->GetReferent(), mirror::Reference::ReferentOffset());
2833     }
2834   }
2835 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static ATTRIBUTE_UNUSED) const2836   void operator()(ObjPtr<mirror::Object> obj,
2837                   MemberOffset offset,
2838                   bool is_static ATTRIBUTE_UNUSED) const
2839       REQUIRES_SHARED(Locks::mutator_lock_) {
2840     VerifyReference(obj.Ptr(), obj->GetFieldObject<mirror::Object>(offset), offset);
2841   }
2842 
IsLive(ObjPtr<mirror::Object> obj) const2843   bool IsLive(ObjPtr<mirror::Object> obj) const NO_THREAD_SAFETY_ANALYSIS {
2844     return heap_->IsLiveObjectLocked(obj, true, false, true);
2845   }
2846 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const2847   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
2848       REQUIRES_SHARED(Locks::mutator_lock_) {
2849     if (!root->IsNull()) {
2850       VisitRoot(root);
2851     }
2852   }
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const2853   void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
2854       REQUIRES_SHARED(Locks::mutator_lock_) {
2855     const_cast<VerifyReferenceVisitor*>(this)->VisitRoot(
2856         root->AsMirrorPtr(), RootInfo(kRootVMInternal));
2857   }
2858 
VisitRoot(mirror::Object * root,const RootInfo & root_info)2859   void VisitRoot(mirror::Object* root, const RootInfo& root_info) override
2860       REQUIRES_SHARED(Locks::mutator_lock_) {
2861     if (root == nullptr) {
2862       LOG(ERROR) << "Root is null with info " << root_info.GetType();
2863     } else if (!VerifyReference(nullptr, root, MemberOffset(0))) {
2864       LOG(ERROR) << "Root " << root << " is dead with type " << mirror::Object::PrettyTypeOf(root)
2865           << " thread_id= " << root_info.GetThreadId() << " root_type= " << root_info.GetType();
2866     }
2867   }
2868 
2869  private:
2870   // TODO: Fix the no thread safety analysis.
2871   // Returns false on failure.
VerifyReference(mirror::Object * obj,mirror::Object * ref,MemberOffset offset) const2872   bool VerifyReference(mirror::Object* obj, mirror::Object* ref, MemberOffset offset) const
2873       NO_THREAD_SAFETY_ANALYSIS {
2874     if (ref == nullptr || IsLive(ref)) {
2875       // Verify that the reference is live.
2876       return true;
2877     }
2878     CHECK_EQ(self_, Thread::Current());  // fail_count_ is private to the calling thread.
2879     *fail_count_ += 1;
2880     if (*fail_count_ == 1) {
2881       // Only print message for the first failure to prevent spam.
2882       LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
2883     }
2884     if (obj != nullptr) {
2885       // Only do this part for non roots.
2886       accounting::CardTable* card_table = heap_->GetCardTable();
2887       accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
2888       accounting::ObjectStack* live_stack = heap_->live_stack_.get();
2889       uint8_t* card_addr = card_table->CardFromAddr(obj);
2890       LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
2891                  << offset << "\n card value = " << static_cast<int>(*card_addr);
2892       if (heap_->IsValidObjectAddress(obj->GetClass())) {
2893         LOG(ERROR) << "Obj type " << obj->PrettyTypeOf();
2894       } else {
2895         LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
2896       }
2897 
2898       // Attempt to find the class inside of the recently freed objects.
2899       space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
2900       if (ref_space != nullptr && ref_space->IsMallocSpace()) {
2901         space::MallocSpace* space = ref_space->AsMallocSpace();
2902         mirror::Class* ref_class = space->FindRecentFreedObject(ref);
2903         if (ref_class != nullptr) {
2904           LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
2905                      << ref_class->PrettyClass();
2906         } else {
2907           LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
2908         }
2909       }
2910 
2911       if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
2912           ref->GetClass()->IsClass()) {
2913         LOG(ERROR) << "Ref type " << ref->PrettyTypeOf();
2914       } else {
2915         LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
2916                    << ") is not a valid heap address";
2917       }
2918 
2919       card_table->CheckAddrIsInCardTable(reinterpret_cast<const uint8_t*>(obj));
2920       void* cover_begin = card_table->AddrFromCard(card_addr);
2921       void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
2922           accounting::CardTable::kCardSize);
2923       LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
2924           << "-" << cover_end;
2925       accounting::ContinuousSpaceBitmap* bitmap =
2926           heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
2927 
2928       if (bitmap == nullptr) {
2929         LOG(ERROR) << "Object " << obj << " has no bitmap";
2930         if (!VerifyClassClass(obj->GetClass())) {
2931           LOG(ERROR) << "Object " << obj << " failed class verification!";
2932         }
2933       } else {
2934         // Print out how the object is live.
2935         if (bitmap->Test(obj)) {
2936           LOG(ERROR) << "Object " << obj << " found in live bitmap";
2937         }
2938         if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
2939           LOG(ERROR) << "Object " << obj << " found in allocation stack";
2940         }
2941         if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
2942           LOG(ERROR) << "Object " << obj << " found in live stack";
2943         }
2944         if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
2945           LOG(ERROR) << "Ref " << ref << " found in allocation stack";
2946         }
2947         if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
2948           LOG(ERROR) << "Ref " << ref << " found in live stack";
2949         }
2950         // Attempt to see if the card table missed the reference.
2951         ScanVisitor scan_visitor;
2952         uint8_t* byte_cover_begin = reinterpret_cast<uint8_t*>(card_table->AddrFromCard(card_addr));
2953         card_table->Scan<false>(bitmap, byte_cover_begin,
2954                                 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
2955       }
2956 
2957       // Search to see if any of the roots reference our object.
2958       RootMatchesObjectVisitor visitor1(obj);
2959       Runtime::Current()->VisitRoots(&visitor1);
2960       // Search to see if any of the roots reference our reference.
2961       RootMatchesObjectVisitor visitor2(ref);
2962       Runtime::Current()->VisitRoots(&visitor2);
2963     }
2964     return false;
2965   }
2966 
2967   Thread* const self_;
2968   Heap* const heap_;
2969   size_t* const fail_count_;
2970   const bool verify_referent_;
2971 };
2972 
2973 // Verify all references within an object, for use with HeapBitmap::Visit.
2974 class VerifyObjectVisitor {
2975  public:
VerifyObjectVisitor(Thread * self,Heap * heap,size_t * fail_count,bool verify_referent)2976   VerifyObjectVisitor(Thread* self, Heap* heap, size_t* fail_count, bool verify_referent)
2977       : self_(self), heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
2978 
operator ()(mirror::Object * obj)2979   void operator()(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2980     // Note: we are verifying the references in obj but not obj itself, this is because obj must
2981     // be live or else how did we find it in the live bitmap?
2982     VerifyReferenceVisitor visitor(self_, heap_, fail_count_, verify_referent_);
2983     // The class doesn't count as a reference but we should verify it anyways.
2984     obj->VisitReferences(visitor, visitor);
2985   }
2986 
VerifyRoots()2987   void VerifyRoots() REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!Locks::heap_bitmap_lock_) {
2988     ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2989     VerifyReferenceVisitor visitor(self_, heap_, fail_count_, verify_referent_);
2990     Runtime::Current()->VisitRoots(&visitor);
2991   }
2992 
GetFailureCount() const2993   uint32_t GetFailureCount() const REQUIRES(Locks::mutator_lock_) {
2994     CHECK_EQ(self_, Thread::Current());
2995     return *fail_count_;
2996   }
2997 
2998  private:
2999   Thread* const self_;
3000   Heap* const heap_;
3001   size_t* const fail_count_;
3002   const bool verify_referent_;
3003 };
3004 
PushOnAllocationStackWithInternalGC(Thread * self,ObjPtr<mirror::Object> * obj)3005 void Heap::PushOnAllocationStackWithInternalGC(Thread* self, ObjPtr<mirror::Object>* obj) {
3006   // Slow path, the allocation stack push back must have already failed.
3007   DCHECK(!allocation_stack_->AtomicPushBack(obj->Ptr()));
3008   do {
3009     // TODO: Add handle VerifyObject.
3010     StackHandleScope<1> hs(self);
3011     HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
3012     // Push our object into the reserve region of the allocation stack. This is only required due
3013     // to heap verification requiring that roots are live (either in the live bitmap or in the
3014     // allocation stack).
3015     CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(obj->Ptr()));
3016     CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
3017   } while (!allocation_stack_->AtomicPushBack(obj->Ptr()));
3018 }
3019 
PushOnThreadLocalAllocationStackWithInternalGC(Thread * self,ObjPtr<mirror::Object> * obj)3020 void Heap::PushOnThreadLocalAllocationStackWithInternalGC(Thread* self,
3021                                                           ObjPtr<mirror::Object>* obj) {
3022   // Slow path, the allocation stack push back must have already failed.
3023   DCHECK(!self->PushOnThreadLocalAllocationStack(obj->Ptr()));
3024   StackReference<mirror::Object>* start_address;
3025   StackReference<mirror::Object>* end_address;
3026   while (!allocation_stack_->AtomicBumpBack(kThreadLocalAllocationStackSize, &start_address,
3027                                             &end_address)) {
3028     // TODO: Add handle VerifyObject.
3029     StackHandleScope<1> hs(self);
3030     HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
3031     // Push our object into the reserve region of the allocaiton stack. This is only required due
3032     // to heap verification requiring that roots are live (either in the live bitmap or in the
3033     // allocation stack).
3034     CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(obj->Ptr()));
3035     // Push into the reserve allocation stack.
3036     CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
3037   }
3038   self->SetThreadLocalAllocationStack(start_address, end_address);
3039   // Retry on the new thread-local allocation stack.
3040   CHECK(self->PushOnThreadLocalAllocationStack(obj->Ptr()));  // Must succeed.
3041 }
3042 
3043 // Must do this with mutators suspended since we are directly accessing the allocation stacks.
VerifyHeapReferences(bool verify_referents)3044 size_t Heap::VerifyHeapReferences(bool verify_referents) {
3045   Thread* self = Thread::Current();
3046   Locks::mutator_lock_->AssertExclusiveHeld(self);
3047   // Lets sort our allocation stacks so that we can efficiently binary search them.
3048   allocation_stack_->Sort();
3049   live_stack_->Sort();
3050   // Since we sorted the allocation stack content, need to revoke all
3051   // thread-local allocation stacks.
3052   RevokeAllThreadLocalAllocationStacks(self);
3053   size_t fail_count = 0;
3054   VerifyObjectVisitor visitor(self, this, &fail_count, verify_referents);
3055   // Verify objects in the allocation stack since these will be objects which were:
3056   // 1. Allocated prior to the GC (pre GC verification).
3057   // 2. Allocated during the GC (pre sweep GC verification).
3058   // We don't want to verify the objects in the live stack since they themselves may be
3059   // pointing to dead objects if they are not reachable.
3060   VisitObjectsPaused(visitor);
3061   // Verify the roots:
3062   visitor.VerifyRoots();
3063   if (visitor.GetFailureCount() > 0) {
3064     // Dump mod-union tables.
3065     for (const auto& table_pair : mod_union_tables_) {
3066       accounting::ModUnionTable* mod_union_table = table_pair.second;
3067       mod_union_table->Dump(LOG_STREAM(ERROR) << mod_union_table->GetName() << ": ");
3068     }
3069     // Dump remembered sets.
3070     for (const auto& table_pair : remembered_sets_) {
3071       accounting::RememberedSet* remembered_set = table_pair.second;
3072       remembered_set->Dump(LOG_STREAM(ERROR) << remembered_set->GetName() << ": ");
3073     }
3074     DumpSpaces(LOG_STREAM(ERROR));
3075   }
3076   return visitor.GetFailureCount();
3077 }
3078 
3079 class VerifyReferenceCardVisitor {
3080  public:
VerifyReferenceCardVisitor(Heap * heap,bool * failed)3081   VerifyReferenceCardVisitor(Heap* heap, bool* failed)
3082       REQUIRES_SHARED(Locks::mutator_lock_,
3083                             Locks::heap_bitmap_lock_)
3084       : heap_(heap), failed_(failed) {
3085   }
3086 
3087   // There is no card marks for native roots on a class.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root ATTRIBUTE_UNUSED) const3088   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
3089       const {}
VisitRoot(mirror::CompressedReference<mirror::Object> * root ATTRIBUTE_UNUSED) const3090   void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
3091 
3092   // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
3093   // annotalysis on visitors.
operator ()(mirror::Object * obj,MemberOffset offset,bool is_static) const3094   void operator()(mirror::Object* obj, MemberOffset offset, bool is_static) const
3095       NO_THREAD_SAFETY_ANALYSIS {
3096     mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
3097     // Filter out class references since changing an object's class does not mark the card as dirty.
3098     // Also handles large objects, since the only reference they hold is a class reference.
3099     if (ref != nullptr && !ref->IsClass()) {
3100       accounting::CardTable* card_table = heap_->GetCardTable();
3101       // If the object is not dirty and it is referencing something in the live stack other than
3102       // class, then it must be on a dirty card.
3103       if (!card_table->AddrIsInCardTable(obj)) {
3104         LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
3105         *failed_ = true;
3106       } else if (!card_table->IsDirty(obj)) {
3107         // TODO: Check mod-union tables.
3108         // Card should be either kCardDirty if it got re-dirtied after we aged it, or
3109         // kCardDirty - 1 if it didnt get touched since we aged it.
3110         accounting::ObjectStack* live_stack = heap_->live_stack_.get();
3111         if (live_stack->ContainsSorted(ref)) {
3112           if (live_stack->ContainsSorted(obj)) {
3113             LOG(ERROR) << "Object " << obj << " found in live stack";
3114           }
3115           if (heap_->GetLiveBitmap()->Test(obj)) {
3116             LOG(ERROR) << "Object " << obj << " found in live bitmap";
3117           }
3118           LOG(ERROR) << "Object " << obj << " " << mirror::Object::PrettyTypeOf(obj)
3119                     << " references " << ref << " " << mirror::Object::PrettyTypeOf(ref)
3120                     << " in live stack";
3121 
3122           // Print which field of the object is dead.
3123           if (!obj->IsObjectArray()) {
3124             ObjPtr<mirror::Class> klass = is_static ? obj->AsClass() : obj->GetClass();
3125             CHECK(klass != nullptr);
3126             for (ArtField& field : (is_static ? klass->GetSFields() : klass->GetIFields())) {
3127               if (field.GetOffset().Int32Value() == offset.Int32Value()) {
3128                 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
3129                            << field.PrettyField();
3130                 break;
3131               }
3132             }
3133           } else {
3134             ObjPtr<mirror::ObjectArray<mirror::Object>> object_array =
3135                 obj->AsObjectArray<mirror::Object>();
3136             for (int32_t i = 0; i < object_array->GetLength(); ++i) {
3137               if (object_array->Get(i) == ref) {
3138                 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
3139               }
3140             }
3141           }
3142 
3143           *failed_ = true;
3144         }
3145       }
3146     }
3147   }
3148 
3149  private:
3150   Heap* const heap_;
3151   bool* const failed_;
3152 };
3153 
3154 class VerifyLiveStackReferences {
3155  public:
VerifyLiveStackReferences(Heap * heap)3156   explicit VerifyLiveStackReferences(Heap* heap)
3157       : heap_(heap),
3158         failed_(false) {}
3159 
operator ()(mirror::Object * obj) const3160   void operator()(mirror::Object* obj) const
3161       REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
3162     VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
3163     obj->VisitReferences(visitor, VoidFunctor());
3164   }
3165 
Failed() const3166   bool Failed() const {
3167     return failed_;
3168   }
3169 
3170  private:
3171   Heap* const heap_;
3172   bool failed_;
3173 };
3174 
VerifyMissingCardMarks()3175 bool Heap::VerifyMissingCardMarks() {
3176   Thread* self = Thread::Current();
3177   Locks::mutator_lock_->AssertExclusiveHeld(self);
3178   // We need to sort the live stack since we binary search it.
3179   live_stack_->Sort();
3180   // Since we sorted the allocation stack content, need to revoke all
3181   // thread-local allocation stacks.
3182   RevokeAllThreadLocalAllocationStacks(self);
3183   VerifyLiveStackReferences visitor(this);
3184   GetLiveBitmap()->Visit(visitor);
3185   // We can verify objects in the live stack since none of these should reference dead objects.
3186   for (auto* it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
3187     if (!kUseThreadLocalAllocationStack || it->AsMirrorPtr() != nullptr) {
3188       visitor(it->AsMirrorPtr());
3189     }
3190   }
3191   return !visitor.Failed();
3192 }
3193 
SwapStacks()3194 void Heap::SwapStacks() {
3195   if (kUseThreadLocalAllocationStack) {
3196     live_stack_->AssertAllZero();
3197   }
3198   allocation_stack_.swap(live_stack_);
3199 }
3200 
RevokeAllThreadLocalAllocationStacks(Thread * self)3201 void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
3202   // This must be called only during the pause.
3203   DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
3204   MutexLock mu(self, *Locks::runtime_shutdown_lock_);
3205   MutexLock mu2(self, *Locks::thread_list_lock_);
3206   std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
3207   for (Thread* t : thread_list) {
3208     t->RevokeThreadLocalAllocationStack();
3209   }
3210 }
3211 
AssertThreadLocalBuffersAreRevoked(Thread * thread)3212 void Heap::AssertThreadLocalBuffersAreRevoked(Thread* thread) {
3213   if (kIsDebugBuild) {
3214     if (rosalloc_space_ != nullptr) {
3215       rosalloc_space_->AssertThreadLocalBuffersAreRevoked(thread);
3216     }
3217     if (bump_pointer_space_ != nullptr) {
3218       bump_pointer_space_->AssertThreadLocalBuffersAreRevoked(thread);
3219     }
3220   }
3221 }
3222 
AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked()3223 void Heap::AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked() {
3224   if (kIsDebugBuild) {
3225     if (bump_pointer_space_ != nullptr) {
3226       bump_pointer_space_->AssertAllThreadLocalBuffersAreRevoked();
3227     }
3228   }
3229 }
3230 
FindModUnionTableFromSpace(space::Space * space)3231 accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
3232   auto it = mod_union_tables_.find(space);
3233   if (it == mod_union_tables_.end()) {
3234     return nullptr;
3235   }
3236   return it->second;
3237 }
3238 
FindRememberedSetFromSpace(space::Space * space)3239 accounting::RememberedSet* Heap::FindRememberedSetFromSpace(space::Space* space) {
3240   auto it = remembered_sets_.find(space);
3241   if (it == remembered_sets_.end()) {
3242     return nullptr;
3243   }
3244   return it->second;
3245 }
3246 
ProcessCards(TimingLogger * timings,bool use_rem_sets,bool process_alloc_space_cards,bool clear_alloc_space_cards)3247 void Heap::ProcessCards(TimingLogger* timings,
3248                         bool use_rem_sets,
3249                         bool process_alloc_space_cards,
3250                         bool clear_alloc_space_cards) {
3251   TimingLogger::ScopedTiming t(__FUNCTION__, timings);
3252   // Clear cards and keep track of cards cleared in the mod-union table.
3253   for (const auto& space : continuous_spaces_) {
3254     accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
3255     accounting::RememberedSet* rem_set = FindRememberedSetFromSpace(space);
3256     if (table != nullptr) {
3257       const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
3258           "ImageModUnionClearCards";
3259       TimingLogger::ScopedTiming t2(name, timings);
3260       table->ProcessCards();
3261     } else if (use_rem_sets && rem_set != nullptr) {
3262       DCHECK(collector::SemiSpace::kUseRememberedSet) << static_cast<int>(collector_type_);
3263       TimingLogger::ScopedTiming t2("AllocSpaceRemSetClearCards", timings);
3264       rem_set->ClearCards();
3265     } else if (process_alloc_space_cards) {
3266       TimingLogger::ScopedTiming t2("AllocSpaceClearCards", timings);
3267       if (clear_alloc_space_cards) {
3268         uint8_t* end = space->End();
3269         if (space->IsImageSpace()) {
3270           // Image space end is the end of the mirror objects, it is not necessarily page or card
3271           // aligned. Align up so that the check in ClearCardRange does not fail.
3272           end = AlignUp(end, accounting::CardTable::kCardSize);
3273         }
3274         card_table_->ClearCardRange(space->Begin(), end);
3275       } else {
3276         // No mod union table for the AllocSpace. Age the cards so that the GC knows that these
3277         // cards were dirty before the GC started.
3278         // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
3279         // -> clean(cleaning thread).
3280         // The races are we either end up with: Aged card, unaged card. Since we have the
3281         // checkpoint roots and then we scan / update mod union tables after. We will always
3282         // scan either card. If we end up with the non aged card, we scan it it in the pause.
3283         card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(),
3284                                        VoidFunctor());
3285       }
3286     }
3287   }
3288 }
3289 
3290 struct IdentityMarkHeapReferenceVisitor : public MarkObjectVisitor {
MarkObjectart::gc::IdentityMarkHeapReferenceVisitor3291   mirror::Object* MarkObject(mirror::Object* obj) override {
3292     return obj;
3293   }
MarkHeapReferenceart::gc::IdentityMarkHeapReferenceVisitor3294   void MarkHeapReference(mirror::HeapReference<mirror::Object>*, bool) override {
3295   }
3296 };
3297 
PreGcVerificationPaused(collector::GarbageCollector * gc)3298 void Heap::PreGcVerificationPaused(collector::GarbageCollector* gc) {
3299   Thread* const self = Thread::Current();
3300   TimingLogger* const timings = current_gc_iteration_.GetTimings();
3301   TimingLogger::ScopedTiming t(__FUNCTION__, timings);
3302   if (verify_pre_gc_heap_) {
3303     TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyHeapReferences", timings);
3304     size_t failures = VerifyHeapReferences();
3305     if (failures > 0) {
3306       LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3307           << " failures";
3308     }
3309   }
3310   // Check that all objects which reference things in the live stack are on dirty cards.
3311   if (verify_missing_card_marks_) {
3312     TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyMissingCardMarks", timings);
3313     ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
3314     SwapStacks();
3315     // Sort the live stack so that we can quickly binary search it later.
3316     CHECK(VerifyMissingCardMarks()) << "Pre " << gc->GetName()
3317                                     << " missing card mark verification failed\n" << DumpSpaces();
3318     SwapStacks();
3319   }
3320   if (verify_mod_union_table_) {
3321     TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyModUnionTables", timings);
3322     ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
3323     for (const auto& table_pair : mod_union_tables_) {
3324       accounting::ModUnionTable* mod_union_table = table_pair.second;
3325       IdentityMarkHeapReferenceVisitor visitor;
3326       mod_union_table->UpdateAndMarkReferences(&visitor);
3327       mod_union_table->Verify();
3328     }
3329   }
3330 }
3331 
PreGcVerification(collector::GarbageCollector * gc)3332 void Heap::PreGcVerification(collector::GarbageCollector* gc) {
3333   if (verify_pre_gc_heap_ || verify_missing_card_marks_ || verify_mod_union_table_) {
3334     collector::GarbageCollector::ScopedPause pause(gc, false);
3335     PreGcVerificationPaused(gc);
3336   }
3337 }
3338 
PrePauseRosAllocVerification(collector::GarbageCollector * gc ATTRIBUTE_UNUSED)3339 void Heap::PrePauseRosAllocVerification(collector::GarbageCollector* gc ATTRIBUTE_UNUSED) {
3340   // TODO: Add a new runtime option for this?
3341   if (verify_pre_gc_rosalloc_) {
3342     RosAllocVerification(current_gc_iteration_.GetTimings(), "PreGcRosAllocVerification");
3343   }
3344 }
3345 
PreSweepingGcVerification(collector::GarbageCollector * gc)3346 void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
3347   Thread* const self = Thread::Current();
3348   TimingLogger* const timings = current_gc_iteration_.GetTimings();
3349   TimingLogger::ScopedTiming t(__FUNCTION__, timings);
3350   // Called before sweeping occurs since we want to make sure we are not going so reclaim any
3351   // reachable objects.
3352   if (verify_pre_sweeping_heap_) {
3353     TimingLogger::ScopedTiming t2("(Paused)PostSweepingVerifyHeapReferences", timings);
3354     CHECK_NE(self->GetState(), kRunnable);
3355     {
3356       WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3357       // Swapping bound bitmaps does nothing.
3358       gc->SwapBitmaps();
3359     }
3360     // Pass in false since concurrent reference processing can mean that the reference referents
3361     // may point to dead objects at the point which PreSweepingGcVerification is called.
3362     size_t failures = VerifyHeapReferences(false);
3363     if (failures > 0) {
3364       LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed with " << failures
3365           << " failures";
3366     }
3367     {
3368       WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3369       gc->SwapBitmaps();
3370     }
3371   }
3372   if (verify_pre_sweeping_rosalloc_) {
3373     RosAllocVerification(timings, "PreSweepingRosAllocVerification");
3374   }
3375 }
3376 
PostGcVerificationPaused(collector::GarbageCollector * gc)3377 void Heap::PostGcVerificationPaused(collector::GarbageCollector* gc) {
3378   // Only pause if we have to do some verification.
3379   Thread* const self = Thread::Current();
3380   TimingLogger* const timings = GetCurrentGcIteration()->GetTimings();
3381   TimingLogger::ScopedTiming t(__FUNCTION__, timings);
3382   if (verify_system_weaks_) {
3383     ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3384     collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
3385     mark_sweep->VerifySystemWeaks();
3386   }
3387   if (verify_post_gc_rosalloc_) {
3388     RosAllocVerification(timings, "(Paused)PostGcRosAllocVerification");
3389   }
3390   if (verify_post_gc_heap_) {
3391     TimingLogger::ScopedTiming t2("(Paused)PostGcVerifyHeapReferences", timings);
3392     size_t failures = VerifyHeapReferences();
3393     if (failures > 0) {
3394       LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3395           << " failures";
3396     }
3397   }
3398 }
3399 
PostGcVerification(collector::GarbageCollector * gc)3400 void Heap::PostGcVerification(collector::GarbageCollector* gc) {
3401   if (verify_system_weaks_ || verify_post_gc_rosalloc_ || verify_post_gc_heap_) {
3402     collector::GarbageCollector::ScopedPause pause(gc, false);
3403     PostGcVerificationPaused(gc);
3404   }
3405 }
3406 
RosAllocVerification(TimingLogger * timings,const char * name)3407 void Heap::RosAllocVerification(TimingLogger* timings, const char* name) {
3408   TimingLogger::ScopedTiming t(name, timings);
3409   for (const auto& space : continuous_spaces_) {
3410     if (space->IsRosAllocSpace()) {
3411       VLOG(heap) << name << " : " << space->GetName();
3412       space->AsRosAllocSpace()->Verify();
3413     }
3414   }
3415 }
3416 
WaitForGcToComplete(GcCause cause,Thread * self)3417 collector::GcType Heap::WaitForGcToComplete(GcCause cause, Thread* self) {
3418   ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
3419   MutexLock mu(self, *gc_complete_lock_);
3420   return WaitForGcToCompleteLocked(cause, self);
3421 }
3422 
WaitForGcToCompleteLocked(GcCause cause,Thread * self)3423 collector::GcType Heap::WaitForGcToCompleteLocked(GcCause cause, Thread* self) {
3424   gc_complete_cond_->CheckSafeToWait(self);
3425   collector::GcType last_gc_type = collector::kGcTypeNone;
3426   GcCause last_gc_cause = kGcCauseNone;
3427   uint64_t wait_start = NanoTime();
3428   while (collector_type_running_ != kCollectorTypeNone) {
3429     if (self != task_processor_->GetRunningThread()) {
3430       // The current thread is about to wait for a currently running
3431       // collection to finish. If the waiting thread is not the heap
3432       // task daemon thread, the currently running collection is
3433       // considered as a blocking GC.
3434       running_collection_is_blocking_ = true;
3435       VLOG(gc) << "Waiting for a blocking GC " << cause;
3436     }
3437     SCOPED_TRACE << "GC: Wait For Completion " << cause;
3438     // We must wait, change thread state then sleep on gc_complete_cond_;
3439     gc_complete_cond_->Wait(self);
3440     last_gc_type = last_gc_type_;
3441     last_gc_cause = last_gc_cause_;
3442   }
3443   uint64_t wait_time = NanoTime() - wait_start;
3444   total_wait_time_ += wait_time;
3445   if (wait_time > long_pause_log_threshold_) {
3446     LOG(INFO) << "WaitForGcToComplete blocked " << cause << " on " << last_gc_cause << " for "
3447               << PrettyDuration(wait_time);
3448   }
3449   if (self != task_processor_->GetRunningThread()) {
3450     // The current thread is about to run a collection. If the thread
3451     // is not the heap task daemon thread, it's considered as a
3452     // blocking GC (i.e., blocking itself).
3453     running_collection_is_blocking_ = true;
3454     // Don't log fake "GC" types that are only used for debugger or hidden APIs. If we log these,
3455     // it results in log spam. kGcCauseExplicit is already logged in LogGC, so avoid it here too.
3456     if (cause == kGcCauseForAlloc ||
3457         cause == kGcCauseForNativeAlloc ||
3458         cause == kGcCauseDisableMovingGc) {
3459       VLOG(gc) << "Starting a blocking GC " << cause;
3460     }
3461   }
3462   return last_gc_type;
3463 }
3464 
DumpForSigQuit(std::ostream & os)3465 void Heap::DumpForSigQuit(std::ostream& os) {
3466   os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
3467      << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
3468   DumpGcPerformanceInfo(os);
3469 }
3470 
GetPercentFree()3471 size_t Heap::GetPercentFree() {
3472   return static_cast<size_t>(100.0f * static_cast<float>(
3473       GetFreeMemory()) / target_footprint_.load(std::memory_order_relaxed));
3474 }
3475 
SetIdealFootprint(size_t target_footprint)3476 void Heap::SetIdealFootprint(size_t target_footprint) {
3477   if (target_footprint > GetMaxMemory()) {
3478     VLOG(gc) << "Clamp target GC heap from " << PrettySize(target_footprint) << " to "
3479              << PrettySize(GetMaxMemory());
3480     target_footprint = GetMaxMemory();
3481   }
3482   target_footprint_.store(target_footprint, std::memory_order_relaxed);
3483 }
3484 
IsMovableObject(ObjPtr<mirror::Object> obj) const3485 bool Heap::IsMovableObject(ObjPtr<mirror::Object> obj) const {
3486   if (kMovingCollector) {
3487     space::Space* space = FindContinuousSpaceFromObject(obj.Ptr(), true);
3488     if (space != nullptr) {
3489       // TODO: Check large object?
3490       return space->CanMoveObjects();
3491     }
3492   }
3493   return false;
3494 }
3495 
FindCollectorByGcType(collector::GcType gc_type)3496 collector::GarbageCollector* Heap::FindCollectorByGcType(collector::GcType gc_type) {
3497   for (auto* collector : garbage_collectors_) {
3498     if (collector->GetCollectorType() == collector_type_ &&
3499         collector->GetGcType() == gc_type) {
3500       return collector;
3501     }
3502   }
3503   return nullptr;
3504 }
3505 
HeapGrowthMultiplier() const3506 double Heap::HeapGrowthMultiplier() const {
3507   // If we don't care about pause times we are background, so return 1.0.
3508   if (!CareAboutPauseTimes()) {
3509     return 1.0;
3510   }
3511   return foreground_heap_growth_multiplier_;
3512 }
3513 
GrowForUtilization(collector::GarbageCollector * collector_ran,size_t bytes_allocated_before_gc)3514 void Heap::GrowForUtilization(collector::GarbageCollector* collector_ran,
3515                               size_t bytes_allocated_before_gc) {
3516   // We know what our utilization is at this moment.
3517   // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
3518   const size_t bytes_allocated = GetBytesAllocated();
3519   // Trace the new heap size after the GC is finished.
3520   TraceHeapSize(bytes_allocated);
3521   uint64_t target_size, grow_bytes;
3522   collector::GcType gc_type = collector_ran->GetGcType();
3523   MutexLock mu(Thread::Current(), process_state_update_lock_);
3524   // Use the multiplier to grow more for foreground.
3525   const double multiplier = HeapGrowthMultiplier();
3526   if (gc_type != collector::kGcTypeSticky) {
3527     // Grow the heap for non sticky GC.
3528     uint64_t delta = bytes_allocated * (1.0 / GetTargetHeapUtilization() - 1.0);
3529     DCHECK_LE(delta, std::numeric_limits<size_t>::max()) << "bytes_allocated=" << bytes_allocated
3530         << " target_utilization_=" << target_utilization_;
3531     grow_bytes = std::min(delta, static_cast<uint64_t>(max_free_));
3532     grow_bytes = std::max(grow_bytes, static_cast<uint64_t>(min_free_));
3533     target_size = bytes_allocated + static_cast<uint64_t>(grow_bytes * multiplier);
3534     next_gc_type_ = collector::kGcTypeSticky;
3535   } else {
3536     collector::GcType non_sticky_gc_type = NonStickyGcType();
3537     // Find what the next non sticky collector will be.
3538     collector::GarbageCollector* non_sticky_collector = FindCollectorByGcType(non_sticky_gc_type);
3539     if (use_generational_cc_) {
3540       if (non_sticky_collector == nullptr) {
3541         non_sticky_collector = FindCollectorByGcType(collector::kGcTypePartial);
3542       }
3543       CHECK(non_sticky_collector != nullptr);
3544     }
3545     double sticky_gc_throughput_adjustment = GetStickyGcThroughputAdjustment(use_generational_cc_);
3546 
3547     // If the throughput of the current sticky GC >= throughput of the non sticky collector, then
3548     // do another sticky collection next.
3549     // We also check that the bytes allocated aren't over the target_footprint, or
3550     // concurrent_start_bytes in case of concurrent GCs, in order to prevent a
3551     // pathological case where dead objects which aren't reclaimed by sticky could get accumulated
3552     // if the sticky GC throughput always remained >= the full/partial throughput.
3553     size_t target_footprint = target_footprint_.load(std::memory_order_relaxed);
3554     if (current_gc_iteration_.GetEstimatedThroughput() * sticky_gc_throughput_adjustment >=
3555         non_sticky_collector->GetEstimatedMeanThroughput() &&
3556         non_sticky_collector->NumberOfIterations() > 0 &&
3557         bytes_allocated <= (IsGcConcurrent() ? concurrent_start_bytes_ : target_footprint)) {
3558       next_gc_type_ = collector::kGcTypeSticky;
3559     } else {
3560       next_gc_type_ = non_sticky_gc_type;
3561     }
3562     // If we have freed enough memory, shrink the heap back down.
3563     const size_t adjusted_max_free = static_cast<size_t>(max_free_ * multiplier);
3564     if (bytes_allocated + adjusted_max_free < target_footprint) {
3565       target_size = bytes_allocated + adjusted_max_free;
3566       grow_bytes = max_free_;
3567     } else {
3568       target_size = std::max(bytes_allocated, target_footprint);
3569       // The same whether jank perceptible or not; just avoid the adjustment.
3570       grow_bytes = 0;
3571     }
3572   }
3573   CHECK_LE(target_size, std::numeric_limits<size_t>::max());
3574   if (!ignore_target_footprint_) {
3575     SetIdealFootprint(target_size);
3576     // Store target size (computed with foreground heap growth multiplier) for updating
3577     // target_footprint_ when process state switches to foreground.
3578     // target_size = 0 ensures that target_footprint_ is not updated on
3579     // process-state switch.
3580     min_foreground_target_footprint_ =
3581         (multiplier <= 1.0 && grow_bytes > 0)
3582         ? bytes_allocated + static_cast<size_t>(grow_bytes * foreground_heap_growth_multiplier_)
3583         : 0;
3584 
3585     if (IsGcConcurrent()) {
3586       const uint64_t freed_bytes = current_gc_iteration_.GetFreedBytes() +
3587           current_gc_iteration_.GetFreedLargeObjectBytes() +
3588           current_gc_iteration_.GetFreedRevokeBytes();
3589       // Bytes allocated will shrink by freed_bytes after the GC runs, so if we want to figure out
3590       // how many bytes were allocated during the GC we need to add freed_bytes back on.
3591       CHECK_GE(bytes_allocated + freed_bytes, bytes_allocated_before_gc);
3592       const size_t bytes_allocated_during_gc = bytes_allocated + freed_bytes -
3593           bytes_allocated_before_gc;
3594       // Calculate when to perform the next ConcurrentGC.
3595       // Estimate how many remaining bytes we will have when we need to start the next GC.
3596       size_t remaining_bytes = bytes_allocated_during_gc;
3597       remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
3598       remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
3599       size_t target_footprint = target_footprint_.load(std::memory_order_relaxed);
3600       if (UNLIKELY(remaining_bytes > target_footprint)) {
3601         // A never going to happen situation that from the estimated allocation rate we will exceed
3602         // the applications entire footprint with the given estimated allocation rate. Schedule
3603         // another GC nearly straight away.
3604         remaining_bytes = std::min(kMinConcurrentRemainingBytes, target_footprint);
3605       }
3606       DCHECK_LE(target_footprint_.load(std::memory_order_relaxed), GetMaxMemory());
3607       // Start a concurrent GC when we get close to the estimated remaining bytes. When the
3608       // allocation rate is very high, remaining_bytes could tell us that we should start a GC
3609       // right away.
3610       concurrent_start_bytes_ = std::max(target_footprint - remaining_bytes, bytes_allocated);
3611     }
3612   }
3613 }
3614 
ClampGrowthLimit()3615 void Heap::ClampGrowthLimit() {
3616   // Use heap bitmap lock to guard against races with BindLiveToMarkBitmap.
3617   ScopedObjectAccess soa(Thread::Current());
3618   WriterMutexLock mu(soa.Self(), *Locks::heap_bitmap_lock_);
3619   capacity_ = growth_limit_;
3620   for (const auto& space : continuous_spaces_) {
3621     if (space->IsMallocSpace()) {
3622       gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3623       malloc_space->ClampGrowthLimit();
3624     }
3625   }
3626   if (collector_type_ == kCollectorTypeCC) {
3627     DCHECK(region_space_ != nullptr);
3628     // Twice the capacity as CC needs extra space for evacuating objects.
3629     region_space_->ClampGrowthLimit(2 * capacity_);
3630   }
3631   // This space isn't added for performance reasons.
3632   if (main_space_backup_.get() != nullptr) {
3633     main_space_backup_->ClampGrowthLimit();
3634   }
3635 }
3636 
ClearGrowthLimit()3637 void Heap::ClearGrowthLimit() {
3638   if (target_footprint_.load(std::memory_order_relaxed) == growth_limit_
3639       && growth_limit_ < capacity_) {
3640     target_footprint_.store(capacity_, std::memory_order_relaxed);
3641     concurrent_start_bytes_ =
3642         UnsignedDifference(capacity_, kMinConcurrentRemainingBytes);
3643   }
3644   growth_limit_ = capacity_;
3645   ScopedObjectAccess soa(Thread::Current());
3646   for (const auto& space : continuous_spaces_) {
3647     if (space->IsMallocSpace()) {
3648       gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3649       malloc_space->ClearGrowthLimit();
3650       malloc_space->SetFootprintLimit(malloc_space->Capacity());
3651     }
3652   }
3653   // This space isn't added for performance reasons.
3654   if (main_space_backup_.get() != nullptr) {
3655     main_space_backup_->ClearGrowthLimit();
3656     main_space_backup_->SetFootprintLimit(main_space_backup_->Capacity());
3657   }
3658 }
3659 
AddFinalizerReference(Thread * self,ObjPtr<mirror::Object> * object)3660 void Heap::AddFinalizerReference(Thread* self, ObjPtr<mirror::Object>* object) {
3661   ScopedObjectAccess soa(self);
3662   ScopedLocalRef<jobject> arg(self->GetJniEnv(), soa.AddLocalReference<jobject>(*object));
3663   jvalue args[1];
3664   args[0].l = arg.get();
3665   InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_FinalizerReference_add, args);
3666   // Restore object in case it gets moved.
3667   *object = soa.Decode<mirror::Object>(arg.get());
3668 }
3669 
RequestConcurrentGCAndSaveObject(Thread * self,bool force_full,ObjPtr<mirror::Object> * obj)3670 void Heap::RequestConcurrentGCAndSaveObject(Thread* self,
3671                                             bool force_full,
3672                                             ObjPtr<mirror::Object>* obj) {
3673   StackHandleScope<1> hs(self);
3674   HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
3675   RequestConcurrentGC(self, kGcCauseBackground, force_full);
3676 }
3677 
3678 class Heap::ConcurrentGCTask : public HeapTask {
3679  public:
ConcurrentGCTask(uint64_t target_time,GcCause cause,bool force_full)3680   ConcurrentGCTask(uint64_t target_time, GcCause cause, bool force_full)
3681       : HeapTask(target_time), cause_(cause), force_full_(force_full) {}
Run(Thread * self)3682   void Run(Thread* self) override {
3683     gc::Heap* heap = Runtime::Current()->GetHeap();
3684     heap->ConcurrentGC(self, cause_, force_full_);
3685     heap->ClearConcurrentGCRequest();
3686   }
3687 
3688  private:
3689   const GcCause cause_;
3690   const bool force_full_;  // If true, force full (or partial) collection.
3691 };
3692 
CanAddHeapTask(Thread * self)3693 static bool CanAddHeapTask(Thread* self) REQUIRES(!Locks::runtime_shutdown_lock_) {
3694   Runtime* runtime = Runtime::Current();
3695   return runtime != nullptr && runtime->IsFinishedStarting() && !runtime->IsShuttingDown(self) &&
3696       !self->IsHandlingStackOverflow();
3697 }
3698 
ClearConcurrentGCRequest()3699 void Heap::ClearConcurrentGCRequest() {
3700   concurrent_gc_pending_.store(false, std::memory_order_relaxed);
3701 }
3702 
RequestConcurrentGC(Thread * self,GcCause cause,bool force_full)3703 void Heap::RequestConcurrentGC(Thread* self, GcCause cause, bool force_full) {
3704   if (CanAddHeapTask(self) &&
3705       concurrent_gc_pending_.CompareAndSetStrongSequentiallyConsistent(false, true)) {
3706     task_processor_->AddTask(self, new ConcurrentGCTask(NanoTime(),  // Start straight away.
3707                                                         cause,
3708                                                         force_full));
3709   }
3710 }
3711 
ConcurrentGC(Thread * self,GcCause cause,bool force_full)3712 void Heap::ConcurrentGC(Thread* self, GcCause cause, bool force_full) {
3713   if (!Runtime::Current()->IsShuttingDown(self)) {
3714     // Wait for any GCs currently running to finish.
3715     if (WaitForGcToComplete(cause, self) == collector::kGcTypeNone) {
3716       // If we can't run the GC type we wanted to run, find the next appropriate one and try
3717       // that instead. E.g. can't do partial, so do full instead.
3718       collector::GcType next_gc_type = next_gc_type_;
3719       // If forcing full and next gc type is sticky, override with a non-sticky type.
3720       if (force_full && next_gc_type == collector::kGcTypeSticky) {
3721         next_gc_type = NonStickyGcType();
3722       }
3723       if (CollectGarbageInternal(next_gc_type, cause, false) == collector::kGcTypeNone) {
3724         for (collector::GcType gc_type : gc_plan_) {
3725           // Attempt to run the collector, if we succeed, we are done.
3726           if (gc_type > next_gc_type &&
3727               CollectGarbageInternal(gc_type, cause, false) != collector::kGcTypeNone) {
3728             break;
3729           }
3730         }
3731       }
3732     }
3733   }
3734 }
3735 
3736 class Heap::CollectorTransitionTask : public HeapTask {
3737  public:
CollectorTransitionTask(uint64_t target_time)3738   explicit CollectorTransitionTask(uint64_t target_time) : HeapTask(target_time) {}
3739 
Run(Thread * self)3740   void Run(Thread* self) override {
3741     gc::Heap* heap = Runtime::Current()->GetHeap();
3742     heap->DoPendingCollectorTransition();
3743     heap->ClearPendingCollectorTransition(self);
3744   }
3745 };
3746 
ClearPendingCollectorTransition(Thread * self)3747 void Heap::ClearPendingCollectorTransition(Thread* self) {
3748   MutexLock mu(self, *pending_task_lock_);
3749   pending_collector_transition_ = nullptr;
3750 }
3751 
RequestCollectorTransition(CollectorType desired_collector_type,uint64_t delta_time)3752 void Heap::RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) {
3753   Thread* self = Thread::Current();
3754   desired_collector_type_ = desired_collector_type;
3755   if (desired_collector_type_ == collector_type_ || !CanAddHeapTask(self)) {
3756     return;
3757   }
3758   if (collector_type_ == kCollectorTypeCC) {
3759     // For CC, we invoke a full compaction when going to the background, but the collector type
3760     // doesn't change.
3761     DCHECK_EQ(desired_collector_type_, kCollectorTypeCCBackground);
3762   }
3763   DCHECK_NE(collector_type_, kCollectorTypeCCBackground);
3764   CollectorTransitionTask* added_task = nullptr;
3765   const uint64_t target_time = NanoTime() + delta_time;
3766   {
3767     MutexLock mu(self, *pending_task_lock_);
3768     // If we have an existing collector transition, update the targe time to be the new target.
3769     if (pending_collector_transition_ != nullptr) {
3770       task_processor_->UpdateTargetRunTime(self, pending_collector_transition_, target_time);
3771       return;
3772     }
3773     added_task = new CollectorTransitionTask(target_time);
3774     pending_collector_transition_ = added_task;
3775   }
3776   task_processor_->AddTask(self, added_task);
3777 }
3778 
3779 class Heap::HeapTrimTask : public HeapTask {
3780  public:
HeapTrimTask(uint64_t delta_time)3781   explicit HeapTrimTask(uint64_t delta_time) : HeapTask(NanoTime() + delta_time) { }
Run(Thread * self)3782   void Run(Thread* self) override {
3783     gc::Heap* heap = Runtime::Current()->GetHeap();
3784     heap->Trim(self);
3785     heap->ClearPendingTrim(self);
3786   }
3787 };
3788 
ClearPendingTrim(Thread * self)3789 void Heap::ClearPendingTrim(Thread* self) {
3790   MutexLock mu(self, *pending_task_lock_);
3791   pending_heap_trim_ = nullptr;
3792 }
3793 
RequestTrim(Thread * self)3794 void Heap::RequestTrim(Thread* self) {
3795   if (!CanAddHeapTask(self)) {
3796     return;
3797   }
3798   // GC completed and now we must decide whether to request a heap trim (advising pages back to the
3799   // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
3800   // a space it will hold its lock and can become a cause of jank.
3801   // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
3802   // forking.
3803 
3804   // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
3805   // because that only marks object heads, so a large array looks like lots of empty space. We
3806   // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
3807   // to utilization (which is probably inversely proportional to how much benefit we can expect).
3808   // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
3809   // not how much use we're making of those pages.
3810   HeapTrimTask* added_task = nullptr;
3811   {
3812     MutexLock mu(self, *pending_task_lock_);
3813     if (pending_heap_trim_ != nullptr) {
3814       // Already have a heap trim request in task processor, ignore this request.
3815       return;
3816     }
3817     added_task = new HeapTrimTask(kHeapTrimWait);
3818     pending_heap_trim_ = added_task;
3819   }
3820   task_processor_->AddTask(self, added_task);
3821 }
3822 
IncrementNumberOfBytesFreedRevoke(size_t freed_bytes_revoke)3823 void Heap::IncrementNumberOfBytesFreedRevoke(size_t freed_bytes_revoke) {
3824   size_t previous_num_bytes_freed_revoke =
3825       num_bytes_freed_revoke_.fetch_add(freed_bytes_revoke, std::memory_order_relaxed);
3826   // Check the updated value is less than the number of bytes allocated. There is a risk of
3827   // execution being suspended between the increment above and the CHECK below, leading to
3828   // the use of previous_num_bytes_freed_revoke in the comparison.
3829   CHECK_GE(num_bytes_allocated_.load(std::memory_order_relaxed),
3830            previous_num_bytes_freed_revoke + freed_bytes_revoke);
3831 }
3832 
RevokeThreadLocalBuffers(Thread * thread)3833 void Heap::RevokeThreadLocalBuffers(Thread* thread) {
3834   if (rosalloc_space_ != nullptr) {
3835     size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3836     if (freed_bytes_revoke > 0U) {
3837       IncrementNumberOfBytesFreedRevoke(freed_bytes_revoke);
3838     }
3839   }
3840   if (bump_pointer_space_ != nullptr) {
3841     CHECK_EQ(bump_pointer_space_->RevokeThreadLocalBuffers(thread), 0U);
3842   }
3843   if (region_space_ != nullptr) {
3844     CHECK_EQ(region_space_->RevokeThreadLocalBuffers(thread), 0U);
3845   }
3846 }
3847 
RevokeRosAllocThreadLocalBuffers(Thread * thread)3848 void Heap::RevokeRosAllocThreadLocalBuffers(Thread* thread) {
3849   if (rosalloc_space_ != nullptr) {
3850     size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3851     if (freed_bytes_revoke > 0U) {
3852       IncrementNumberOfBytesFreedRevoke(freed_bytes_revoke);
3853     }
3854   }
3855 }
3856 
RevokeAllThreadLocalBuffers()3857 void Heap::RevokeAllThreadLocalBuffers() {
3858   if (rosalloc_space_ != nullptr) {
3859     size_t freed_bytes_revoke = rosalloc_space_->RevokeAllThreadLocalBuffers();
3860     if (freed_bytes_revoke > 0U) {
3861       IncrementNumberOfBytesFreedRevoke(freed_bytes_revoke);
3862     }
3863   }
3864   if (bump_pointer_space_ != nullptr) {
3865     CHECK_EQ(bump_pointer_space_->RevokeAllThreadLocalBuffers(), 0U);
3866   }
3867   if (region_space_ != nullptr) {
3868     CHECK_EQ(region_space_->RevokeAllThreadLocalBuffers(), 0U);
3869   }
3870 }
3871 
IsGCRequestPending() const3872 bool Heap::IsGCRequestPending() const {
3873   return concurrent_gc_pending_.load(std::memory_order_relaxed);
3874 }
3875 
RunFinalization(JNIEnv * env,uint64_t timeout)3876 void Heap::RunFinalization(JNIEnv* env, uint64_t timeout) {
3877   env->CallStaticVoidMethod(WellKnownClasses::dalvik_system_VMRuntime,
3878                             WellKnownClasses::dalvik_system_VMRuntime_runFinalization,
3879                             static_cast<jlong>(timeout));
3880 }
3881 
3882 // For GC triggering purposes, we count old (pre-last-GC) and new native allocations as
3883 // different fractions of Java allocations.
3884 // For now, we essentially do not count old native allocations at all, so that we can preserve the
3885 // existing behavior of not limiting native heap size. If we seriously considered it, we would
3886 // have to adjust collection thresholds when we encounter large amounts of old native memory,
3887 // and handle native out-of-memory situations.
3888 
3889 static constexpr size_t kOldNativeDiscountFactor = 65536;  // Approximately infinite for now.
3890 static constexpr size_t kNewNativeDiscountFactor = 2;
3891 
3892 // If weighted java + native memory use exceeds our target by kStopForNativeFactor, and
3893 // newly allocated memory exceeds stop_for_native_allocs_, we wait for GC to complete to avoid
3894 // running out of memory.
3895 static constexpr float kStopForNativeFactor = 4.0;
3896 
3897 // Return the ratio of the weighted native + java allocated bytes to its target value.
3898 // A return value > 1.0 means we should collect. Significantly larger values mean we're falling
3899 // behind.
NativeMemoryOverTarget(size_t current_native_bytes,bool is_gc_concurrent)3900 inline float Heap::NativeMemoryOverTarget(size_t current_native_bytes, bool is_gc_concurrent) {
3901   // Collection check for native allocation. Does not enforce Java heap bounds.
3902   // With adj_start_bytes defined below, effectively checks
3903   // <java bytes allocd> + c1*<old native allocd> + c2*<new native allocd) >= adj_start_bytes,
3904   // where c3 > 1, and currently c1 and c2 are 1 divided by the values defined above.
3905   size_t old_native_bytes = old_native_bytes_allocated_.load(std::memory_order_relaxed);
3906   if (old_native_bytes > current_native_bytes) {
3907     // Net decrease; skip the check, but update old value.
3908     // It's OK to lose an update if two stores race.
3909     old_native_bytes_allocated_.store(current_native_bytes, std::memory_order_relaxed);
3910     return 0.0;
3911   } else {
3912     size_t new_native_bytes = UnsignedDifference(current_native_bytes, old_native_bytes);
3913     size_t weighted_native_bytes = new_native_bytes / kNewNativeDiscountFactor
3914         + old_native_bytes / kOldNativeDiscountFactor;
3915     size_t add_bytes_allowed = static_cast<size_t>(
3916         NativeAllocationGcWatermark() * HeapGrowthMultiplier());
3917     size_t java_gc_start_bytes = is_gc_concurrent
3918         ? concurrent_start_bytes_
3919         : target_footprint_.load(std::memory_order_relaxed);
3920     size_t adj_start_bytes = UnsignedSum(java_gc_start_bytes,
3921                                          add_bytes_allowed / kNewNativeDiscountFactor);
3922     return static_cast<float>(GetBytesAllocated() + weighted_native_bytes)
3923          / static_cast<float>(adj_start_bytes);
3924   }
3925 }
3926 
CheckGCForNative(Thread * self)3927 inline void Heap::CheckGCForNative(Thread* self) {
3928   bool is_gc_concurrent = IsGcConcurrent();
3929   size_t current_native_bytes = GetNativeBytes();
3930   float gc_urgency = NativeMemoryOverTarget(current_native_bytes, is_gc_concurrent);
3931   if (UNLIKELY(gc_urgency >= 1.0)) {
3932     if (is_gc_concurrent) {
3933       RequestConcurrentGC(self, kGcCauseForNativeAlloc, /*force_full=*/true);
3934       if (gc_urgency > kStopForNativeFactor
3935           && current_native_bytes > stop_for_native_allocs_) {
3936         // We're in danger of running out of memory due to rampant native allocation.
3937         if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
3938           LOG(INFO) << "Stopping for native allocation, urgency: " << gc_urgency;
3939         }
3940         WaitForGcToComplete(kGcCauseForNativeAlloc, self);
3941       }
3942     } else {
3943       CollectGarbageInternal(NonStickyGcType(), kGcCauseForNativeAlloc, false);
3944     }
3945   }
3946 }
3947 
3948 // About kNotifyNativeInterval allocations have occurred. Check whether we should garbage collect.
NotifyNativeAllocations(JNIEnv * env)3949 void Heap::NotifyNativeAllocations(JNIEnv* env) {
3950   native_objects_notified_.fetch_add(kNotifyNativeInterval, std::memory_order_relaxed);
3951   CheckGCForNative(ThreadForEnv(env));
3952 }
3953 
3954 // Register a native allocation with an explicit size.
3955 // This should only be done for large allocations of non-malloc memory, which we wouldn't
3956 // otherwise see.
RegisterNativeAllocation(JNIEnv * env,size_t bytes)3957 void Heap::RegisterNativeAllocation(JNIEnv* env, size_t bytes) {
3958   // Cautiously check for a wrapped negative bytes argument.
3959   DCHECK(sizeof(size_t) < 8 || bytes < (std::numeric_limits<size_t>::max() / 2));
3960   native_bytes_registered_.fetch_add(bytes, std::memory_order_relaxed);
3961   uint32_t objects_notified =
3962       native_objects_notified_.fetch_add(1, std::memory_order_relaxed);
3963   if (objects_notified % kNotifyNativeInterval == kNotifyNativeInterval - 1
3964       || bytes > kCheckImmediatelyThreshold) {
3965     CheckGCForNative(ThreadForEnv(env));
3966   }
3967 }
3968 
RegisterNativeFree(JNIEnv *,size_t bytes)3969 void Heap::RegisterNativeFree(JNIEnv*, size_t bytes) {
3970   size_t allocated;
3971   size_t new_freed_bytes;
3972   do {
3973     allocated = native_bytes_registered_.load(std::memory_order_relaxed);
3974     new_freed_bytes = std::min(allocated, bytes);
3975     // We should not be registering more free than allocated bytes.
3976     // But correctly keep going in non-debug builds.
3977     DCHECK_EQ(new_freed_bytes, bytes);
3978   } while (!native_bytes_registered_.CompareAndSetWeakRelaxed(allocated,
3979                                                               allocated - new_freed_bytes));
3980 }
3981 
GetTotalMemory() const3982 size_t Heap::GetTotalMemory() const {
3983   return std::max(target_footprint_.load(std::memory_order_relaxed), GetBytesAllocated());
3984 }
3985 
AddModUnionTable(accounting::ModUnionTable * mod_union_table)3986 void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
3987   DCHECK(mod_union_table != nullptr);
3988   mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
3989 }
3990 
CheckPreconditionsForAllocObject(ObjPtr<mirror::Class> c,size_t byte_count)3991 void Heap::CheckPreconditionsForAllocObject(ObjPtr<mirror::Class> c, size_t byte_count) {
3992   // Compare rounded sizes since the allocation may have been retried after rounding the size.
3993   // See b/37885600
3994   CHECK(c == nullptr || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
3995         (c->IsVariableSize() ||
3996             RoundUp(c->GetObjectSize(), kObjectAlignment) ==
3997                 RoundUp(byte_count, kObjectAlignment)))
3998       << "ClassFlags=" << c->GetClassFlags()
3999       << " IsClassClass=" << c->IsClassClass()
4000       << " byte_count=" << byte_count
4001       << " IsVariableSize=" << c->IsVariableSize()
4002       << " ObjectSize=" << c->GetObjectSize()
4003       << " sizeof(Class)=" << sizeof(mirror::Class)
4004       << " " << verification_->DumpObjectInfo(c.Ptr(), /*tag=*/ "klass");
4005   CHECK_GE(byte_count, sizeof(mirror::Object));
4006 }
4007 
AddRememberedSet(accounting::RememberedSet * remembered_set)4008 void Heap::AddRememberedSet(accounting::RememberedSet* remembered_set) {
4009   CHECK(remembered_set != nullptr);
4010   space::Space* space = remembered_set->GetSpace();
4011   CHECK(space != nullptr);
4012   CHECK(remembered_sets_.find(space) == remembered_sets_.end()) << space;
4013   remembered_sets_.Put(space, remembered_set);
4014   CHECK(remembered_sets_.find(space) != remembered_sets_.end()) << space;
4015 }
4016 
RemoveRememberedSet(space::Space * space)4017 void Heap::RemoveRememberedSet(space::Space* space) {
4018   CHECK(space != nullptr);
4019   auto it = remembered_sets_.find(space);
4020   CHECK(it != remembered_sets_.end());
4021   delete it->second;
4022   remembered_sets_.erase(it);
4023   CHECK(remembered_sets_.find(space) == remembered_sets_.end());
4024 }
4025 
ClearMarkedObjects()4026 void Heap::ClearMarkedObjects() {
4027   // Clear all of the spaces' mark bitmaps.
4028   for (const auto& space : GetContinuousSpaces()) {
4029     if (space->GetLiveBitmap() != nullptr && !space->HasBoundBitmaps()) {
4030       space->GetMarkBitmap()->Clear();
4031     }
4032   }
4033   // Clear the marked objects in the discontinous space object sets.
4034   for (const auto& space : GetDiscontinuousSpaces()) {
4035     space->GetMarkBitmap()->Clear();
4036   }
4037 }
4038 
SetAllocationRecords(AllocRecordObjectMap * records)4039 void Heap::SetAllocationRecords(AllocRecordObjectMap* records) {
4040   allocation_records_.reset(records);
4041 }
4042 
VisitAllocationRecords(RootVisitor * visitor) const4043 void Heap::VisitAllocationRecords(RootVisitor* visitor) const {
4044   if (IsAllocTrackingEnabled()) {
4045     MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4046     if (IsAllocTrackingEnabled()) {
4047       GetAllocationRecords()->VisitRoots(visitor);
4048     }
4049   }
4050 }
4051 
SweepAllocationRecords(IsMarkedVisitor * visitor) const4052 void Heap::SweepAllocationRecords(IsMarkedVisitor* visitor) const {
4053   if (IsAllocTrackingEnabled()) {
4054     MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4055     if (IsAllocTrackingEnabled()) {
4056       GetAllocationRecords()->SweepAllocationRecords(visitor);
4057     }
4058   }
4059 }
4060 
AllowNewAllocationRecords() const4061 void Heap::AllowNewAllocationRecords() const {
4062   CHECK(!kUseReadBarrier);
4063   MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4064   AllocRecordObjectMap* allocation_records = GetAllocationRecords();
4065   if (allocation_records != nullptr) {
4066     allocation_records->AllowNewAllocationRecords();
4067   }
4068 }
4069 
DisallowNewAllocationRecords() const4070 void Heap::DisallowNewAllocationRecords() const {
4071   CHECK(!kUseReadBarrier);
4072   MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4073   AllocRecordObjectMap* allocation_records = GetAllocationRecords();
4074   if (allocation_records != nullptr) {
4075     allocation_records->DisallowNewAllocationRecords();
4076   }
4077 }
4078 
BroadcastForNewAllocationRecords() const4079 void Heap::BroadcastForNewAllocationRecords() const {
4080   // Always broadcast without checking IsAllocTrackingEnabled() because IsAllocTrackingEnabled() may
4081   // be set to false while some threads are waiting for system weak access in
4082   // AllocRecordObjectMap::RecordAllocation() and we may fail to wake them up. b/27467554.
4083   MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4084   AllocRecordObjectMap* allocation_records = GetAllocationRecords();
4085   if (allocation_records != nullptr) {
4086     allocation_records->BroadcastForNewAllocationRecords();
4087   }
4088 }
4089 
CheckGcStressMode(Thread * self,ObjPtr<mirror::Object> * obj)4090 void Heap::CheckGcStressMode(Thread* self, ObjPtr<mirror::Object>* obj) {
4091   DCHECK(gc_stress_mode_);
4092   auto* const runtime = Runtime::Current();
4093   if (runtime->GetClassLinker()->IsInitialized() && !runtime->IsActiveTransaction()) {
4094     // Check if we should GC.
4095     bool new_backtrace = false;
4096     {
4097       static constexpr size_t kMaxFrames = 16u;
4098       MutexLock mu(self, *backtrace_lock_);
4099       FixedSizeBacktrace<kMaxFrames> backtrace;
4100       backtrace.Collect(/* skip_count= */ 2);
4101       uint64_t hash = backtrace.Hash();
4102       new_backtrace = seen_backtraces_.find(hash) == seen_backtraces_.end();
4103       if (new_backtrace) {
4104         seen_backtraces_.insert(hash);
4105       }
4106     }
4107     if (new_backtrace) {
4108       StackHandleScope<1> hs(self);
4109       auto h = hs.NewHandleWrapper(obj);
4110       CollectGarbage(/* clear_soft_references= */ false);
4111       unique_backtrace_count_.fetch_add(1);
4112     } else {
4113       seen_backtrace_count_.fetch_add(1);
4114     }
4115   }
4116 }
4117 
DisableGCForShutdown()4118 void Heap::DisableGCForShutdown() {
4119   Thread* const self = Thread::Current();
4120   CHECK(Runtime::Current()->IsShuttingDown(self));
4121   MutexLock mu(self, *gc_complete_lock_);
4122   gc_disabled_for_shutdown_ = true;
4123 }
4124 
ObjectIsInBootImageSpace(ObjPtr<mirror::Object> obj) const4125 bool Heap::ObjectIsInBootImageSpace(ObjPtr<mirror::Object> obj) const {
4126   DCHECK_EQ(IsBootImageAddress(obj.Ptr()),
4127             any_of(boot_image_spaces_.begin(),
4128                    boot_image_spaces_.end(),
4129                    [obj](gc::space::ImageSpace* space) REQUIRES_SHARED(Locks::mutator_lock_) {
4130                      return space->HasAddress(obj.Ptr());
4131                    }));
4132   return IsBootImageAddress(obj.Ptr());
4133 }
4134 
IsInBootImageOatFile(const void * p) const4135 bool Heap::IsInBootImageOatFile(const void* p) const {
4136   DCHECK_EQ(IsBootImageAddress(p),
4137             any_of(boot_image_spaces_.begin(),
4138                    boot_image_spaces_.end(),
4139                    [p](gc::space::ImageSpace* space) REQUIRES_SHARED(Locks::mutator_lock_) {
4140                      return space->GetOatFile()->Contains(p);
4141                    }));
4142   return IsBootImageAddress(p);
4143 }
4144 
SetAllocationListener(AllocationListener * l)4145 void Heap::SetAllocationListener(AllocationListener* l) {
4146   AllocationListener* old = GetAndOverwriteAllocationListener(&alloc_listener_, l);
4147 
4148   if (old == nullptr) {
4149     Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
4150   }
4151 }
4152 
RemoveAllocationListener()4153 void Heap::RemoveAllocationListener() {
4154   AllocationListener* old = GetAndOverwriteAllocationListener(&alloc_listener_, nullptr);
4155 
4156   if (old != nullptr) {
4157     Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
4158   }
4159 }
4160 
SetGcPauseListener(GcPauseListener * l)4161 void Heap::SetGcPauseListener(GcPauseListener* l) {
4162   gc_pause_listener_.store(l, std::memory_order_relaxed);
4163 }
4164 
RemoveGcPauseListener()4165 void Heap::RemoveGcPauseListener() {
4166   gc_pause_listener_.store(nullptr, std::memory_order_relaxed);
4167 }
4168 
AllocWithNewTLAB(Thread * self,size_t alloc_size,bool grow,size_t * bytes_allocated,size_t * usable_size,size_t * bytes_tl_bulk_allocated)4169 mirror::Object* Heap::AllocWithNewTLAB(Thread* self,
4170                                        size_t alloc_size,
4171                                        bool grow,
4172                                        size_t* bytes_allocated,
4173                                        size_t* usable_size,
4174                                        size_t* bytes_tl_bulk_allocated) {
4175   const AllocatorType allocator_type = GetCurrentAllocator();
4176   if (kUsePartialTlabs && alloc_size <= self->TlabRemainingCapacity()) {
4177     DCHECK_GT(alloc_size, self->TlabSize());
4178     // There is enough space if we grow the TLAB. Lets do that. This increases the
4179     // TLAB bytes.
4180     const size_t min_expand_size = alloc_size - self->TlabSize();
4181     const size_t expand_bytes = std::max(
4182         min_expand_size,
4183         std::min(self->TlabRemainingCapacity() - self->TlabSize(), kPartialTlabSize));
4184     if (UNLIKELY(IsOutOfMemoryOnAllocation(allocator_type, expand_bytes, grow))) {
4185       return nullptr;
4186     }
4187     *bytes_tl_bulk_allocated = expand_bytes;
4188     self->ExpandTlab(expand_bytes);
4189     DCHECK_LE(alloc_size, self->TlabSize());
4190   } else if (allocator_type == kAllocatorTypeTLAB) {
4191     DCHECK(bump_pointer_space_ != nullptr);
4192     const size_t new_tlab_size = alloc_size + kDefaultTLABSize;
4193     if (UNLIKELY(IsOutOfMemoryOnAllocation(allocator_type, new_tlab_size, grow))) {
4194       return nullptr;
4195     }
4196     // Try allocating a new thread local buffer, if the allocation fails the space must be
4197     // full so return null.
4198     if (!bump_pointer_space_->AllocNewTlab(self, new_tlab_size)) {
4199       return nullptr;
4200     }
4201     *bytes_tl_bulk_allocated = new_tlab_size;
4202   } else {
4203     DCHECK(allocator_type == kAllocatorTypeRegionTLAB);
4204     DCHECK(region_space_ != nullptr);
4205     if (space::RegionSpace::kRegionSize >= alloc_size) {
4206       // Non-large. Check OOME for a tlab.
4207       if (LIKELY(!IsOutOfMemoryOnAllocation(allocator_type,
4208                                             space::RegionSpace::kRegionSize,
4209                                             grow))) {
4210         const size_t new_tlab_size = kUsePartialTlabs
4211             ? std::max(alloc_size, kPartialTlabSize)
4212             : gc::space::RegionSpace::kRegionSize;
4213         // Try to allocate a tlab.
4214         if (!region_space_->AllocNewTlab(self, new_tlab_size, bytes_tl_bulk_allocated)) {
4215           // Failed to allocate a tlab. Try non-tlab.
4216           return region_space_->AllocNonvirtual<false>(alloc_size,
4217                                                        bytes_allocated,
4218                                                        usable_size,
4219                                                        bytes_tl_bulk_allocated);
4220         }
4221         // Fall-through to using the TLAB below.
4222       } else {
4223         // Check OOME for a non-tlab allocation.
4224         if (!IsOutOfMemoryOnAllocation(allocator_type, alloc_size, grow)) {
4225           return region_space_->AllocNonvirtual<false>(alloc_size,
4226                                                        bytes_allocated,
4227                                                        usable_size,
4228                                                        bytes_tl_bulk_allocated);
4229         }
4230         // Neither tlab or non-tlab works. Give up.
4231         return nullptr;
4232       }
4233     } else {
4234       // Large. Check OOME.
4235       if (LIKELY(!IsOutOfMemoryOnAllocation(allocator_type, alloc_size, grow))) {
4236         return region_space_->AllocNonvirtual<false>(alloc_size,
4237                                                      bytes_allocated,
4238                                                      usable_size,
4239                                                      bytes_tl_bulk_allocated);
4240       }
4241       return nullptr;
4242     }
4243   }
4244   // Refilled TLAB, return.
4245   mirror::Object* ret = self->AllocTlab(alloc_size);
4246   DCHECK(ret != nullptr);
4247   *bytes_allocated = alloc_size;
4248   *usable_size = alloc_size;
4249   return ret;
4250 }
4251 
GetVerification() const4252 const Verification* Heap::GetVerification() const {
4253   return verification_.get();
4254 }
4255 
VlogHeapGrowth(size_t old_footprint,size_t new_footprint,size_t alloc_size)4256 void Heap::VlogHeapGrowth(size_t old_footprint, size_t new_footprint, size_t alloc_size) {
4257   VLOG(heap) << "Growing heap from " << PrettySize(old_footprint) << " to "
4258              << PrettySize(new_footprint) << " for a " << PrettySize(alloc_size) << " allocation";
4259 }
4260 
4261 class Heap::TriggerPostForkCCGcTask : public HeapTask {
4262  public:
TriggerPostForkCCGcTask(uint64_t target_time)4263   explicit TriggerPostForkCCGcTask(uint64_t target_time) : HeapTask(target_time) {}
Run(Thread * self)4264   void Run(Thread* self) override {
4265     gc::Heap* heap = Runtime::Current()->GetHeap();
4266     // Trigger a GC, if not already done. The first GC after fork, whenever it
4267     // takes place, will adjust the thresholds to normal levels.
4268     if (heap->target_footprint_.load(std::memory_order_relaxed) == heap->growth_limit_) {
4269       heap->RequestConcurrentGC(self, kGcCauseBackground, false);
4270     }
4271   }
4272 };
4273 
PostForkChildAction(Thread * self)4274 void Heap::PostForkChildAction(Thread* self) {
4275   // Temporarily increase target_footprint_ and concurrent_start_bytes_ to
4276   // max values to avoid GC during app launch.
4277   if (collector_type_ == kCollectorTypeCC && !IsLowMemoryMode()) {
4278     // Set target_footprint_ to the largest allowed value.
4279     SetIdealFootprint(growth_limit_);
4280     // Set concurrent_start_bytes_ to half of the heap size.
4281     size_t target_footprint = target_footprint_.load(std::memory_order_relaxed);
4282     concurrent_start_bytes_ = std::max(target_footprint / 2, GetBytesAllocated());
4283 
4284     GetTaskProcessor()->AddTask(
4285         self, new TriggerPostForkCCGcTask(NanoTime() + MsToNs(kPostForkMaxHeapDurationMS)));
4286   }
4287 }
4288 
VisitReflectiveTargets(ReflectiveValueVisitor * visit)4289 void Heap::VisitReflectiveTargets(ReflectiveValueVisitor *visit) {
4290   VisitObjectsPaused([&visit](mirror::Object* ref) NO_THREAD_SAFETY_ANALYSIS {
4291     art::ObjPtr<mirror::Class> klass(ref->GetClass());
4292     // All these classes are in the BootstrapClassLoader.
4293     if (!klass->IsBootStrapClassLoaded()) {
4294       return;
4295     }
4296     if (GetClassRoot<mirror::Method>()->IsAssignableFrom(klass) ||
4297         GetClassRoot<mirror::Constructor>()->IsAssignableFrom(klass)) {
4298       down_cast<mirror::Executable*>(ref)->VisitTarget(visit);
4299     } else if (art::GetClassRoot<art::mirror::Field>() == klass) {
4300       down_cast<mirror::Field*>(ref)->VisitTarget(visit);
4301     } else if (art::GetClassRoot<art::mirror::MethodHandle>()->IsAssignableFrom(klass)) {
4302       down_cast<mirror::MethodHandle*>(ref)->VisitTarget(visit);
4303     } else if (art::GetClassRoot<art::mirror::FieldVarHandle>()->IsAssignableFrom(klass)) {
4304       down_cast<mirror::FieldVarHandle*>(ref)->VisitTarget(visit);
4305     } else if (art::GetClassRoot<art::mirror::DexCache>()->IsAssignableFrom(klass)) {
4306       down_cast<mirror::DexCache*>(ref)->VisitReflectiveTargets(visit);
4307     }
4308   });
4309 }
4310 
AddHeapTask(gc::HeapTask * task)4311 bool Heap::AddHeapTask(gc::HeapTask* task) {
4312   Thread* const self = Thread::Current();
4313   if (!CanAddHeapTask(self)) {
4314     return false;
4315   }
4316   GetTaskProcessor()->AddTask(self, task);
4317   return true;
4318 }
4319 
4320 }  // namespace gc
4321 }  // namespace art
4322