heap.cc revision c5d085c955244be1743c33227384e5b62076b8bd
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#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <cutils/trace.h>
21
22#include <limits>
23#include <memory>
24#include <vector>
25
26#include "base/allocator.h"
27#include "base/histogram-inl.h"
28#include "base/stl_util.h"
29#include "common_throws.h"
30#include "cutils/sched_policy.h"
31#include "debugger.h"
32#include "gc/accounting/atomic_stack.h"
33#include "gc/accounting/card_table-inl.h"
34#include "gc/accounting/heap_bitmap-inl.h"
35#include "gc/accounting/mod_union_table.h"
36#include "gc/accounting/mod_union_table-inl.h"
37#include "gc/accounting/remembered_set.h"
38#include "gc/accounting/space_bitmap-inl.h"
39#include "gc/collector/concurrent_copying.h"
40#include "gc/collector/mark_compact.h"
41#include "gc/collector/mark_sweep-inl.h"
42#include "gc/collector/partial_mark_sweep.h"
43#include "gc/collector/semi_space.h"
44#include "gc/collector/sticky_mark_sweep.h"
45#include "gc/reference_processor.h"
46#include "gc/space/bump_pointer_space.h"
47#include "gc/space/dlmalloc_space-inl.h"
48#include "gc/space/image_space.h"
49#include "gc/space/large_object_space.h"
50#include "gc/space/rosalloc_space-inl.h"
51#include "gc/space/space-inl.h"
52#include "gc/space/zygote_space.h"
53#include "entrypoints/quick/quick_alloc_entrypoints.h"
54#include "heap-inl.h"
55#include "image.h"
56#include "intern_table.h"
57#include "mirror/art_field-inl.h"
58#include "mirror/class-inl.h"
59#include "mirror/object.h"
60#include "mirror/object-inl.h"
61#include "mirror/object_array-inl.h"
62#include "mirror/reference-inl.h"
63#include "os.h"
64#include "reflection.h"
65#include "runtime.h"
66#include "ScopedLocalRef.h"
67#include "scoped_thread_state_change.h"
68#include "handle_scope-inl.h"
69#include "thread_list.h"
70#include "well_known_classes.h"
71
72namespace art {
73
74namespace gc {
75
76static constexpr size_t kCollectorTransitionStressIterations = 0;
77static constexpr size_t kCollectorTransitionStressWait = 10 * 1000;  // Microseconds
78static constexpr bool kGCALotMode = false;
79static constexpr size_t kGcAlotInterval = KB;
80// Minimum amount of remaining bytes before a concurrent GC is triggered.
81static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
82static constexpr size_t kMaxConcurrentRemainingBytes = 512 * KB;
83// Sticky GC throughput adjustment, divided by 4. Increasing this causes sticky GC to occur more
84// relative to partial/full GC. This may be desirable since sticky GCs interfere less with mutator
85// threads (lower pauses, use less memory bandwidth).
86static constexpr double kStickyGcThroughputAdjustment = 1.0;
87// Whether or not we use the free list large object space. Only use it if USE_ART_LOW_4G_ALLOCATOR
88// since this means that we have to use the slow msync loop in MemMap::MapAnonymous.
89#if USE_ART_LOW_4G_ALLOCATOR
90static constexpr bool kUseFreeListSpaceForLOS = true;
91#else
92static constexpr bool kUseFreeListSpaceForLOS = false;
93#endif
94// Whether or not we compact the zygote in PreZygoteFork.
95static constexpr bool kCompactZygote = kMovingCollector;
96// How many reserve entries are at the end of the allocation stack, these are only needed if the
97// allocation stack overflows.
98static constexpr size_t kAllocationStackReserveSize = 1024;
99// Default mark stack size in bytes.
100static const size_t kDefaultMarkStackSize = 64 * KB;
101// Define space name.
102static const char* kDlMallocSpaceName[2] = {"main dlmalloc space", "main dlmalloc space 1"};
103static const char* kRosAllocSpaceName[2] = {"main rosalloc space", "main rosalloc space 1"};
104static const char* kMemMapSpaceName[2] = {"main space", "main space 1"};
105static const char* kNonMovingSpaceName = "non moving space";
106static const char* kZygoteSpaceName = "zygote space";
107static constexpr size_t kGSSBumpPointerSpaceCapacity = 32 * MB;
108
109Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
110           double target_utilization, double foreground_heap_growth_multiplier,
111           size_t capacity, size_t non_moving_space_capacity, const std::string& image_file_name,
112           const InstructionSet image_instruction_set, CollectorType foreground_collector_type,
113           CollectorType background_collector_type, size_t parallel_gc_threads,
114           size_t conc_gc_threads, bool low_memory_mode,
115           size_t long_pause_log_threshold, size_t long_gc_log_threshold,
116           bool ignore_max_footprint, bool use_tlab,
117           bool verify_pre_gc_heap, bool verify_pre_sweeping_heap, bool verify_post_gc_heap,
118           bool verify_pre_gc_rosalloc, bool verify_pre_sweeping_rosalloc,
119           bool verify_post_gc_rosalloc, bool use_homogeneous_space_compaction_for_oom,
120           uint64_t min_interval_homogeneous_space_compaction_by_oom)
121    : non_moving_space_(nullptr),
122      rosalloc_space_(nullptr),
123      dlmalloc_space_(nullptr),
124      main_space_(nullptr),
125      collector_type_(kCollectorTypeNone),
126      foreground_collector_type_(foreground_collector_type),
127      background_collector_type_(background_collector_type),
128      desired_collector_type_(foreground_collector_type_),
129      heap_trim_request_lock_(nullptr),
130      last_trim_time_(0),
131      heap_transition_or_trim_target_time_(0),
132      heap_trim_request_pending_(false),
133      parallel_gc_threads_(parallel_gc_threads),
134      conc_gc_threads_(conc_gc_threads),
135      low_memory_mode_(low_memory_mode),
136      long_pause_log_threshold_(long_pause_log_threshold),
137      long_gc_log_threshold_(long_gc_log_threshold),
138      ignore_max_footprint_(ignore_max_footprint),
139      zygote_creation_lock_("zygote creation lock", kZygoteCreationLock),
140      have_zygote_space_(false),
141      large_object_threshold_(std::numeric_limits<size_t>::max()),  // Starts out disabled.
142      collector_type_running_(kCollectorTypeNone),
143      last_gc_type_(collector::kGcTypeNone),
144      next_gc_type_(collector::kGcTypePartial),
145      capacity_(capacity),
146      growth_limit_(growth_limit),
147      max_allowed_footprint_(initial_size),
148      native_footprint_gc_watermark_(initial_size),
149      native_need_to_run_finalization_(false),
150      // Initially assume we perceive jank in case the process state is never updated.
151      process_state_(kProcessStateJankPerceptible),
152      concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
153      total_bytes_freed_ever_(0),
154      total_objects_freed_ever_(0),
155      num_bytes_allocated_(0),
156      native_bytes_allocated_(0),
157      verify_missing_card_marks_(false),
158      verify_system_weaks_(false),
159      verify_pre_gc_heap_(verify_pre_gc_heap),
160      verify_pre_sweeping_heap_(verify_pre_sweeping_heap),
161      verify_post_gc_heap_(verify_post_gc_heap),
162      verify_mod_union_table_(false),
163      verify_pre_gc_rosalloc_(verify_pre_gc_rosalloc),
164      verify_pre_sweeping_rosalloc_(verify_pre_sweeping_rosalloc),
165      verify_post_gc_rosalloc_(verify_post_gc_rosalloc),
166      last_gc_time_ns_(NanoTime()),
167      allocation_rate_(0),
168      /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
169       * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
170       * verification is enabled, we limit the size of allocation stacks to speed up their
171       * searching.
172       */
173      max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
174          : (kVerifyObjectSupport > kVerifyObjectModeFast) ? KB : MB),
175      current_allocator_(kAllocatorTypeDlMalloc),
176      current_non_moving_allocator_(kAllocatorTypeNonMoving),
177      bump_pointer_space_(nullptr),
178      temp_space_(nullptr),
179      min_free_(min_free),
180      max_free_(max_free),
181      target_utilization_(target_utilization),
182      foreground_heap_growth_multiplier_(foreground_heap_growth_multiplier),
183      total_wait_time_(0),
184      total_allocation_time_(0),
185      verify_object_mode_(kVerifyObjectModeDisabled),
186      disable_moving_gc_count_(0),
187      running_on_valgrind_(Runtime::Current()->RunningOnValgrind()),
188      use_tlab_(use_tlab),
189      main_space_backup_(nullptr),
190      min_interval_homogeneous_space_compaction_by_oom_(
191          min_interval_homogeneous_space_compaction_by_oom),
192      last_time_homogeneous_space_compaction_by_oom_(NanoTime()),
193      use_homogeneous_space_compaction_for_oom_(use_homogeneous_space_compaction_for_oom) {
194  if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
195    LOG(INFO) << "Heap() entering";
196  }
197  // If we aren't the zygote, switch to the default non zygote allocator. This may update the
198  // entrypoints.
199  const bool is_zygote = Runtime::Current()->IsZygote();
200  if (!is_zygote) {
201    large_object_threshold_ = kDefaultLargeObjectThreshold;
202    // Background compaction is currently not supported for command line runs.
203    if (background_collector_type_ != foreground_collector_type_) {
204      VLOG(heap) << "Disabling background compaction for non zygote";
205      background_collector_type_ = foreground_collector_type_;
206    }
207  }
208  ChangeCollector(desired_collector_type_);
209  live_bitmap_.reset(new accounting::HeapBitmap(this));
210  mark_bitmap_.reset(new accounting::HeapBitmap(this));
211  // Requested begin for the alloc space, to follow the mapped image and oat files
212  byte* requested_alloc_space_begin = nullptr;
213  if (!image_file_name.empty()) {
214    std::string error_msg;
215    space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name.c_str(),
216                                                               image_instruction_set,
217                                                               &error_msg);
218    if (image_space != nullptr) {
219      AddSpace(image_space);
220      // Oat files referenced by image files immediately follow them in memory, ensure alloc space
221      // isn't going to get in the middle
222      byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
223      CHECK_GT(oat_file_end_addr, image_space->End());
224      requested_alloc_space_begin = AlignUp(oat_file_end_addr, kPageSize);
225    } else {
226      LOG(WARNING) << "Could not create image space with image file '" << image_file_name << "'. "
227                   << "Attempting to fall back to imageless running. Error was: " << error_msg;
228    }
229  }
230  /*
231  requested_alloc_space_begin ->     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
232                                     +-  nonmoving space (non_moving_space_capacity)+-
233                                     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
234                                     +-????????????????????????????????????????????+-
235                                     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
236                                     +-main alloc space / bump space 1 (capacity_) +-
237                                     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
238                                     +-????????????????????????????????????????????+-
239                                     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
240                                     +-main alloc space2 / bump space 2 (capacity_)+-
241                                     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
242  */
243  // We don't have hspace compaction enabled with GSS.
244  if (foreground_collector_type_ == kCollectorTypeGSS) {
245    use_homogeneous_space_compaction_for_oom_ = false;
246  }
247  bool support_homogeneous_space_compaction =
248      background_collector_type_ == gc::kCollectorTypeHomogeneousSpaceCompact ||
249      use_homogeneous_space_compaction_for_oom_;
250  // We may use the same space the main space for the non moving space if we don't need to compact
251  // from the main space.
252  // This is not the case if we support homogeneous compaction or have a moving background
253  // collector type.
254  bool separate_non_moving_space = is_zygote ||
255      support_homogeneous_space_compaction || IsMovingGc(foreground_collector_type_) ||
256      IsMovingGc(background_collector_type_);
257  if (foreground_collector_type == kCollectorTypeGSS) {
258    separate_non_moving_space = false;
259  }
260  std::unique_ptr<MemMap> main_mem_map_1;
261  std::unique_ptr<MemMap> main_mem_map_2;
262  byte* request_begin = requested_alloc_space_begin;
263  if (request_begin != nullptr && separate_non_moving_space) {
264    request_begin += non_moving_space_capacity;
265  }
266  std::string error_str;
267  std::unique_ptr<MemMap> non_moving_space_mem_map;
268  if (separate_non_moving_space) {
269    // If we are the zygote, the non moving space becomes the zygote space when we run
270    // PreZygoteFork the first time. In this case, call the map "zygote space" since we can't
271    // rename the mem map later.
272    const char* space_name = is_zygote ? kZygoteSpaceName: kNonMovingSpaceName;
273    // Reserve the non moving mem map before the other two since it needs to be at a specific
274    // address.
275    non_moving_space_mem_map.reset(
276        MemMap::MapAnonymous(space_name, requested_alloc_space_begin,
277                             non_moving_space_capacity, PROT_READ | PROT_WRITE, true, &error_str));
278    CHECK(non_moving_space_mem_map != nullptr) << error_str;
279    // Try to reserve virtual memory at a lower address if we have a separate non moving space.
280    request_begin = reinterpret_cast<byte*>(300 * MB);
281  }
282  // Attempt to create 2 mem maps at or after the requested begin.
283  main_mem_map_1.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[0], request_begin, capacity_,
284                                                    PROT_READ | PROT_WRITE, &error_str));
285  CHECK(main_mem_map_1.get() != nullptr) << error_str;
286  if (support_homogeneous_space_compaction ||
287      background_collector_type_ == kCollectorTypeSS ||
288      foreground_collector_type_ == kCollectorTypeSS) {
289    main_mem_map_2.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[1], main_mem_map_1->End(),
290                                                      capacity_, PROT_READ | PROT_WRITE,
291                                                      &error_str));
292    CHECK(main_mem_map_2.get() != nullptr) << error_str;
293  }
294  // Create the non moving space first so that bitmaps don't take up the address range.
295  if (separate_non_moving_space) {
296    // Non moving space is always dlmalloc since we currently don't have support for multiple
297    // active rosalloc spaces.
298    const size_t size = non_moving_space_mem_map->Size();
299    non_moving_space_ = space::DlMallocSpace::CreateFromMemMap(
300        non_moving_space_mem_map.release(), "zygote / non moving space", kDefaultStartingSize,
301        initial_size, size, size, false);
302    non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
303    CHECK(non_moving_space_ != nullptr) << "Failed creating non moving space "
304        << requested_alloc_space_begin;
305    AddSpace(non_moving_space_);
306  }
307  // Create other spaces based on whether or not we have a moving GC.
308  if (IsMovingGc(foreground_collector_type_) && foreground_collector_type_ != kCollectorTypeGSS) {
309    // Create bump pointer spaces.
310    // We only to create the bump pointer if the foreground collector is a compacting GC.
311    // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
312    bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 1",
313                                                                    main_mem_map_1.release());
314    CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
315    AddSpace(bump_pointer_space_);
316    temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
317                                                            main_mem_map_2.release());
318    CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
319    AddSpace(temp_space_);
320    CHECK(separate_non_moving_space);
321  } else {
322    CreateMainMallocSpace(main_mem_map_1.release(), initial_size, growth_limit_, capacity_);
323    CHECK(main_space_ != nullptr);
324    AddSpace(main_space_);
325    if (!separate_non_moving_space) {
326      non_moving_space_ = main_space_;
327      CHECK(!non_moving_space_->CanMoveObjects());
328    }
329    if (foreground_collector_type_ == kCollectorTypeGSS) {
330      CHECK_EQ(foreground_collector_type_, background_collector_type_);
331      // Create bump pointer spaces instead of a backup space.
332      main_mem_map_2.release();
333      bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space 1",
334                                                            kGSSBumpPointerSpaceCapacity, nullptr);
335      CHECK(bump_pointer_space_ != nullptr);
336      AddSpace(bump_pointer_space_);
337      temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2",
338                                                    kGSSBumpPointerSpaceCapacity, nullptr);
339      CHECK(temp_space_ != nullptr);
340      AddSpace(temp_space_);
341    } else if (main_mem_map_2.get() != nullptr) {
342      const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
343      main_space_backup_.reset(CreateMallocSpaceFromMemMap(main_mem_map_2.release(), initial_size,
344                                                           growth_limit_, capacity_, name, true));
345      CHECK(main_space_backup_.get() != nullptr);
346      // Add the space so its accounted for in the heap_begin and heap_end.
347      AddSpace(main_space_backup_.get());
348    }
349  }
350  CHECK(non_moving_space_ != nullptr);
351  CHECK(!non_moving_space_->CanMoveObjects());
352  // Allocate the large object space.
353  if (kUseFreeListSpaceForLOS) {
354    large_object_space_ = space::FreeListSpace::Create("large object space", nullptr, capacity_);
355  } else {
356    large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
357  }
358  CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
359  AddSpace(large_object_space_);
360  // Compute heap capacity. Continuous spaces are sorted in order of Begin().
361  CHECK(!continuous_spaces_.empty());
362  // Relies on the spaces being sorted.
363  byte* heap_begin = continuous_spaces_.front()->Begin();
364  byte* heap_end = continuous_spaces_.back()->Limit();
365  size_t heap_capacity = heap_end - heap_begin;
366  // Remove the main backup space since it slows down the GC to have unused extra spaces.
367  if (main_space_backup_.get() != nullptr) {
368    RemoveSpace(main_space_backup_.get());
369  }
370  // Allocate the card table.
371  card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
372  CHECK(card_table_.get() != NULL) << "Failed to create card table";
373  // Card cache for now since it makes it easier for us to update the references to the copying
374  // spaces.
375  accounting::ModUnionTable* mod_union_table =
376      new accounting::ModUnionTableToZygoteAllocspace("Image mod-union table", this,
377                                                      GetImageSpace());
378  CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
379  AddModUnionTable(mod_union_table);
380  if (collector::SemiSpace::kUseRememberedSet && non_moving_space_ != main_space_) {
381    accounting::RememberedSet* non_moving_space_rem_set =
382        new accounting::RememberedSet("Non-moving space remembered set", this, non_moving_space_);
383    CHECK(non_moving_space_rem_set != nullptr) << "Failed to create non-moving space remembered set";
384    AddRememberedSet(non_moving_space_rem_set);
385  }
386  // TODO: Count objects in the image space here?
387  num_bytes_allocated_.StoreRelaxed(0);
388  mark_stack_.reset(accounting::ObjectStack::Create("mark stack", kDefaultMarkStackSize,
389                                                    kDefaultMarkStackSize));
390  const size_t alloc_stack_capacity = max_allocation_stack_size_ + kAllocationStackReserveSize;
391  allocation_stack_.reset(accounting::ObjectStack::Create(
392      "allocation stack", max_allocation_stack_size_, alloc_stack_capacity));
393  live_stack_.reset(accounting::ObjectStack::Create(
394      "live stack", max_allocation_stack_size_, alloc_stack_capacity));
395  // It's still too early to take a lock because there are no threads yet, but we can create locks
396  // now. We don't create it earlier to make it clear that you can't use locks during heap
397  // initialization.
398  gc_complete_lock_ = new Mutex("GC complete lock");
399  gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
400                                                *gc_complete_lock_));
401  heap_trim_request_lock_ = new Mutex("Heap trim request lock");
402  last_gc_size_ = GetBytesAllocated();
403  if (ignore_max_footprint_) {
404    SetIdealFootprint(std::numeric_limits<size_t>::max());
405    concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
406  }
407  CHECK_NE(max_allowed_footprint_, 0U);
408  // Create our garbage collectors.
409  for (size_t i = 0; i < 2; ++i) {
410    const bool concurrent = i != 0;
411    garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
412    garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
413    garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
414  }
415  if (kMovingCollector) {
416    // TODO: Clean this up.
417    const bool generational = foreground_collector_type_ == kCollectorTypeGSS;
418    semi_space_collector_ = new collector::SemiSpace(this, generational,
419                                                     generational ? "generational" : "");
420    garbage_collectors_.push_back(semi_space_collector_);
421    concurrent_copying_collector_ = new collector::ConcurrentCopying(this);
422    garbage_collectors_.push_back(concurrent_copying_collector_);
423    mark_compact_collector_ = new collector::MarkCompact(this);
424    garbage_collectors_.push_back(mark_compact_collector_);
425  }
426  if (GetImageSpace() != nullptr && non_moving_space_ != nullptr) {
427    // Check that there's no gap between the image space and the non moving space so that the
428    // immune region won't break (eg. due to a large object allocated in the gap).
429    bool no_gap = MemMap::CheckNoGaps(GetImageSpace()->GetMemMap(),
430                                      non_moving_space_->GetMemMap());
431    if (!no_gap) {
432      MemMap::DumpMaps(LOG(ERROR));
433      LOG(FATAL) << "There's a gap between the image space and the main space";
434    }
435  }
436  if (running_on_valgrind_) {
437    Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
438  }
439  if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
440    LOG(INFO) << "Heap() exiting";
441  }
442}
443
444MemMap* Heap::MapAnonymousPreferredAddress(const char* name, byte* request_begin, size_t capacity,
445                                           int prot_flags, std::string* out_error_str) {
446  while (true) {
447    MemMap* map = MemMap::MapAnonymous(kMemMapSpaceName[0], request_begin, capacity,
448                                       PROT_READ | PROT_WRITE, true, out_error_str);
449    if (map != nullptr || request_begin == nullptr) {
450      return map;
451    }
452    // Retry a  second time with no specified request begin.
453    request_begin = nullptr;
454  }
455  return nullptr;
456}
457
458space::MallocSpace* Heap::CreateMallocSpaceFromMemMap(MemMap* mem_map, size_t initial_size,
459                                                      size_t growth_limit, size_t capacity,
460                                                      const char* name, bool can_move_objects) {
461  space::MallocSpace* malloc_space = nullptr;
462  if (kUseRosAlloc) {
463    // Create rosalloc space.
464    malloc_space = space::RosAllocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
465                                                          initial_size, growth_limit, capacity,
466                                                          low_memory_mode_, can_move_objects);
467  } else {
468    malloc_space = space::DlMallocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
469                                                          initial_size, growth_limit, capacity,
470                                                          can_move_objects);
471  }
472  if (collector::SemiSpace::kUseRememberedSet) {
473    accounting::RememberedSet* rem_set  =
474        new accounting::RememberedSet(std::string(name) + " remembered set", this, malloc_space);
475    CHECK(rem_set != nullptr) << "Failed to create main space remembered set";
476    AddRememberedSet(rem_set);
477  }
478  CHECK(malloc_space != nullptr) << "Failed to create " << name;
479  malloc_space->SetFootprintLimit(malloc_space->Capacity());
480  return malloc_space;
481}
482
483void Heap::CreateMainMallocSpace(MemMap* mem_map, size_t initial_size, size_t growth_limit,
484                                 size_t capacity) {
485  // Is background compaction is enabled?
486  bool can_move_objects = IsMovingGc(background_collector_type_) !=
487      IsMovingGc(foreground_collector_type_) || use_homogeneous_space_compaction_for_oom_;
488  // If we are the zygote and don't yet have a zygote space, it means that the zygote fork will
489  // happen in the future. If this happens and we have kCompactZygote enabled we wish to compact
490  // from the main space to the zygote space. If background compaction is enabled, always pass in
491  // that we can move objets.
492  if (kCompactZygote && Runtime::Current()->IsZygote() && !can_move_objects) {
493    // After the zygote we want this to be false if we don't have background compaction enabled so
494    // that getting primitive array elements is faster.
495    // We never have homogeneous compaction with GSS and don't need a space with movable objects.
496    can_move_objects = !have_zygote_space_ && foreground_collector_type_ != kCollectorTypeGSS;
497  }
498  if (collector::SemiSpace::kUseRememberedSet && main_space_ != nullptr) {
499    RemoveRememberedSet(main_space_);
500  }
501  const char* name = kUseRosAlloc ? kRosAllocSpaceName[0] : kDlMallocSpaceName[0];
502  main_space_ = CreateMallocSpaceFromMemMap(mem_map, initial_size, growth_limit, capacity, name,
503                                            can_move_objects);
504  SetSpaceAsDefault(main_space_);
505  VLOG(heap) << "Created main space " << main_space_;
506}
507
508void Heap::ChangeAllocator(AllocatorType allocator) {
509  if (current_allocator_ != allocator) {
510    // These two allocators are only used internally and don't have any entrypoints.
511    CHECK_NE(allocator, kAllocatorTypeLOS);
512    CHECK_NE(allocator, kAllocatorTypeNonMoving);
513    current_allocator_ = allocator;
514    MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
515    SetQuickAllocEntryPointsAllocator(current_allocator_);
516    Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
517  }
518}
519
520void Heap::DisableMovingGc() {
521  if (IsMovingGc(foreground_collector_type_)) {
522    foreground_collector_type_ = kCollectorTypeCMS;
523  }
524  if (IsMovingGc(background_collector_type_)) {
525    background_collector_type_ = foreground_collector_type_;
526  }
527  TransitionCollector(foreground_collector_type_);
528  ThreadList* tl = Runtime::Current()->GetThreadList();
529  Thread* self = Thread::Current();
530  ScopedThreadStateChange tsc(self, kSuspended);
531  tl->SuspendAll();
532  // Something may have caused the transition to fail.
533  if (!IsMovingGc(collector_type_) && non_moving_space_ != main_space_) {
534    CHECK(main_space_ != nullptr);
535    // The allocation stack may have non movable objects in it. We need to flush it since the GC
536    // can't only handle marking allocation stack objects of one non moving space and one main
537    // space.
538    {
539      WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
540      FlushAllocStack();
541    }
542    main_space_->DisableMovingObjects();
543    non_moving_space_ = main_space_;
544    CHECK(!non_moving_space_->CanMoveObjects());
545  }
546  tl->ResumeAll();
547}
548
549std::string Heap::SafeGetClassDescriptor(mirror::Class* klass) {
550  if (!IsValidContinuousSpaceObjectAddress(klass)) {
551    return StringPrintf("<non heap address klass %p>", klass);
552  }
553  mirror::Class* component_type = klass->GetComponentType<kVerifyNone>();
554  if (IsValidContinuousSpaceObjectAddress(component_type) && klass->IsArrayClass<kVerifyNone>()) {
555    std::string result("[");
556    result += SafeGetClassDescriptor(component_type);
557    return result;
558  } else if (UNLIKELY(klass->IsPrimitive<kVerifyNone>())) {
559    return Primitive::Descriptor(klass->GetPrimitiveType<kVerifyNone>());
560  } else if (UNLIKELY(klass->IsProxyClass<kVerifyNone>())) {
561    return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(klass);
562  } else {
563    mirror::DexCache* dex_cache = klass->GetDexCache<kVerifyNone>();
564    if (!IsValidContinuousSpaceObjectAddress(dex_cache)) {
565      return StringPrintf("<non heap address dex_cache %p>", dex_cache);
566    }
567    const DexFile* dex_file = dex_cache->GetDexFile();
568    uint16_t class_def_idx = klass->GetDexClassDefIndex();
569    if (class_def_idx == DexFile::kDexNoIndex16) {
570      return "<class def not found>";
571    }
572    const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
573    const DexFile::TypeId& type_id = dex_file->GetTypeId(class_def.class_idx_);
574    return dex_file->GetTypeDescriptor(type_id);
575  }
576}
577
578std::string Heap::SafePrettyTypeOf(mirror::Object* obj) {
579  if (obj == nullptr) {
580    return "null";
581  }
582  mirror::Class* klass = obj->GetClass<kVerifyNone>();
583  if (klass == nullptr) {
584    return "(class=null)";
585  }
586  std::string result(SafeGetClassDescriptor(klass));
587  if (obj->IsClass()) {
588    result += "<" + SafeGetClassDescriptor(obj->AsClass<kVerifyNone>()) + ">";
589  }
590  return result;
591}
592
593void Heap::DumpObject(std::ostream& stream, mirror::Object* obj) {
594  if (obj == nullptr) {
595    stream << "(obj=null)";
596    return;
597  }
598  if (IsAligned<kObjectAlignment>(obj)) {
599    space::Space* space = nullptr;
600    // Don't use find space since it only finds spaces which actually contain objects instead of
601    // spaces which may contain objects (e.g. cleared bump pointer spaces).
602    for (const auto& cur_space : continuous_spaces_) {
603      if (cur_space->HasAddress(obj)) {
604        space = cur_space;
605        break;
606      }
607    }
608    // Unprotect all the spaces.
609    for (const auto& space : continuous_spaces_) {
610      mprotect(space->Begin(), space->Capacity(), PROT_READ | PROT_WRITE);
611    }
612    stream << "Object " << obj;
613    if (space != nullptr) {
614      stream << " in space " << *space;
615    }
616    mirror::Class* klass = obj->GetClass<kVerifyNone>();
617    stream << "\nclass=" << klass;
618    if (klass != nullptr) {
619      stream << " type= " << SafePrettyTypeOf(obj);
620    }
621    // Re-protect the address we faulted on.
622    mprotect(AlignDown(obj, kPageSize), kPageSize, PROT_NONE);
623  }
624}
625
626bool Heap::IsCompilingBoot() const {
627  if (!Runtime::Current()->IsCompiler()) {
628    return false;
629  }
630  for (const auto& space : continuous_spaces_) {
631    if (space->IsImageSpace() || space->IsZygoteSpace()) {
632      return false;
633    }
634  }
635  return true;
636}
637
638bool Heap::HasImageSpace() const {
639  for (const auto& space : continuous_spaces_) {
640    if (space->IsImageSpace()) {
641      return true;
642    }
643  }
644  return false;
645}
646
647void Heap::IncrementDisableMovingGC(Thread* self) {
648  // Need to do this holding the lock to prevent races where the GC is about to run / running when
649  // we attempt to disable it.
650  ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
651  MutexLock mu(self, *gc_complete_lock_);
652  ++disable_moving_gc_count_;
653  if (IsMovingGc(collector_type_running_)) {
654    WaitForGcToCompleteLocked(kGcCauseDisableMovingGc, self);
655  }
656}
657
658void Heap::DecrementDisableMovingGC(Thread* self) {
659  MutexLock mu(self, *gc_complete_lock_);
660  CHECK_GE(disable_moving_gc_count_, 0U);
661  --disable_moving_gc_count_;
662}
663
664void Heap::UpdateProcessState(ProcessState process_state) {
665  if (process_state_ != process_state) {
666    process_state_ = process_state;
667    for (size_t i = 1; i <= kCollectorTransitionStressIterations; ++i) {
668      // Start at index 1 to avoid "is always false" warning.
669      // Have iteration 1 always transition the collector.
670      TransitionCollector((((i & 1) == 1) == (process_state_ == kProcessStateJankPerceptible))
671                          ? foreground_collector_type_ : background_collector_type_);
672      usleep(kCollectorTransitionStressWait);
673    }
674    if (process_state_ == kProcessStateJankPerceptible) {
675      // Transition back to foreground right away to prevent jank.
676      RequestCollectorTransition(foreground_collector_type_, 0);
677    } else {
678      // Don't delay for debug builds since we may want to stress test the GC.
679      // If background_collector_type_ is kCollectorTypeHomogeneousSpaceCompact then we have
680      // special handling which does a homogenous space compaction once but then doesn't transition
681      // the collector.
682      RequestCollectorTransition(background_collector_type_,
683                                 kIsDebugBuild ? 0 : kCollectorTransitionWait);
684    }
685  }
686}
687
688void Heap::CreateThreadPool() {
689  const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
690  if (num_threads != 0) {
691    thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
692  }
693}
694
695void Heap::VisitObjects(ObjectCallback callback, void* arg) {
696  Thread* self = Thread::Current();
697  // GCs can move objects, so don't allow this.
698  const char* old_cause = self->StartAssertNoThreadSuspension("Visiting objects");
699  if (bump_pointer_space_ != nullptr) {
700    // Visit objects in bump pointer space.
701    bump_pointer_space_->Walk(callback, arg);
702  }
703  // TODO: Switch to standard begin and end to use ranged a based loop.
704  for (mirror::Object** it = allocation_stack_->Begin(), **end = allocation_stack_->End();
705      it < end; ++it) {
706    mirror::Object* obj = *it;
707    if (obj != nullptr && obj->GetClass() != nullptr) {
708      // Avoid the race condition caused by the object not yet being written into the allocation
709      // stack or the class not yet being written in the object. Or, if kUseThreadLocalAllocationStack,
710      // there can be nulls on the allocation stack.
711      callback(obj, arg);
712    }
713  }
714  GetLiveBitmap()->Walk(callback, arg);
715  self->EndAssertNoThreadSuspension(old_cause);
716}
717
718void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
719  space::ContinuousSpace* space1 = main_space_ != nullptr ? main_space_ : non_moving_space_;
720  space::ContinuousSpace* space2 = non_moving_space_;
721  // TODO: Generalize this to n bitmaps?
722  CHECK(space1 != nullptr);
723  CHECK(space2 != nullptr);
724  MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
725                 large_object_space_->GetLiveBitmap(), stack);
726}
727
728void Heap::DeleteThreadPool() {
729  thread_pool_.reset(nullptr);
730}
731
732void Heap::AddSpace(space::Space* space) {
733  CHECK(space != nullptr);
734  WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
735  if (space->IsContinuousSpace()) {
736    DCHECK(!space->IsDiscontinuousSpace());
737    space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
738    // Continuous spaces don't necessarily have bitmaps.
739    accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
740    accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
741    if (live_bitmap != nullptr) {
742      CHECK(mark_bitmap != nullptr);
743      live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
744      mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
745    }
746    continuous_spaces_.push_back(continuous_space);
747    // Ensure that spaces remain sorted in increasing order of start address.
748    std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
749              [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
750      return a->Begin() < b->Begin();
751    });
752  } else {
753    CHECK(space->IsDiscontinuousSpace());
754    space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
755    live_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
756    mark_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
757    discontinuous_spaces_.push_back(discontinuous_space);
758  }
759  if (space->IsAllocSpace()) {
760    alloc_spaces_.push_back(space->AsAllocSpace());
761  }
762}
763
764void Heap::SetSpaceAsDefault(space::ContinuousSpace* continuous_space) {
765  WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
766  if (continuous_space->IsDlMallocSpace()) {
767    dlmalloc_space_ = continuous_space->AsDlMallocSpace();
768  } else if (continuous_space->IsRosAllocSpace()) {
769    rosalloc_space_ = continuous_space->AsRosAllocSpace();
770  }
771}
772
773void Heap::RemoveSpace(space::Space* space) {
774  DCHECK(space != nullptr);
775  WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
776  if (space->IsContinuousSpace()) {
777    DCHECK(!space->IsDiscontinuousSpace());
778    space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
779    // Continuous spaces don't necessarily have bitmaps.
780    accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
781    accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
782    if (live_bitmap != nullptr) {
783      DCHECK(mark_bitmap != nullptr);
784      live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
785      mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
786    }
787    auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
788    DCHECK(it != continuous_spaces_.end());
789    continuous_spaces_.erase(it);
790  } else {
791    DCHECK(space->IsDiscontinuousSpace());
792    space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
793    live_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
794    mark_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
795    auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
796                        discontinuous_space);
797    DCHECK(it != discontinuous_spaces_.end());
798    discontinuous_spaces_.erase(it);
799  }
800  if (space->IsAllocSpace()) {
801    auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
802    DCHECK(it != alloc_spaces_.end());
803    alloc_spaces_.erase(it);
804  }
805}
806
807void Heap::DumpGcPerformanceInfo(std::ostream& os) {
808  // Dump cumulative timings.
809  os << "Dumping cumulative Gc timings\n";
810  uint64_t total_duration = 0;
811  // Dump cumulative loggers for each GC type.
812  uint64_t total_paused_time = 0;
813  for (auto& collector : garbage_collectors_) {
814    const CumulativeLogger& logger = collector->GetCumulativeTimings();
815    const size_t iterations = logger.GetIterations();
816    const Histogram<uint64_t>& pause_histogram = collector->GetPauseHistogram();
817    if (iterations != 0 && pause_histogram.SampleSize() != 0) {
818      os << ConstDumpable<CumulativeLogger>(logger);
819      const uint64_t total_ns = logger.GetTotalNs();
820      const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
821      double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
822      const uint64_t freed_bytes = collector->GetTotalFreedBytes();
823      const uint64_t freed_objects = collector->GetTotalFreedObjects();
824      Histogram<uint64_t>::CumulativeData cumulative_data;
825      pause_histogram.CreateHistogram(&cumulative_data);
826      pause_histogram.PrintConfidenceIntervals(os, 0.99, cumulative_data);
827      os << collector->GetName() << " total time: " << PrettyDuration(total_ns)
828         << " mean time: " << PrettyDuration(total_ns / iterations) << "\n"
829         << collector->GetName() << " freed: " << freed_objects
830         << " objects with total size " << PrettySize(freed_bytes) << "\n"
831         << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
832         << PrettySize(freed_bytes / seconds) << "/s\n";
833      total_duration += total_ns;
834      total_paused_time += total_pause_ns;
835    }
836    collector->ResetMeasurements();
837  }
838  uint64_t allocation_time =
839      static_cast<uint64_t>(total_allocation_time_.LoadRelaxed()) * kTimeAdjust;
840  if (total_duration != 0) {
841    const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
842    os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
843    os << "Mean GC size throughput: "
844       << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
845    os << "Mean GC object throughput: "
846       << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
847  }
848  uint64_t total_objects_allocated = GetObjectsAllocatedEver();
849  os << "Total number of allocations " << total_objects_allocated << "\n";
850  uint64_t total_bytes_allocated = GetBytesAllocatedEver();
851  os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
852  os << "Free memory " << PrettySize(GetFreeMemory()) << "\n";
853  os << "Free memory until GC " << PrettySize(GetFreeMemoryUntilGC()) << "\n";
854  os << "Free memory until OOME " << PrettySize(GetFreeMemoryUntilOOME()) << "\n";
855  os << "Total memory " << PrettySize(GetTotalMemory()) << "\n";
856  os << "Max memory " << PrettySize(GetMaxMemory()) << "\n";
857  if (kMeasureAllocationTime) {
858    os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
859    os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
860       << "\n";
861  }
862  os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
863  os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
864  BaseMutex::DumpAll(os);
865}
866
867Heap::~Heap() {
868  VLOG(heap) << "Starting ~Heap()";
869  STLDeleteElements(&garbage_collectors_);
870  // If we don't reset then the mark stack complains in its destructor.
871  allocation_stack_->Reset();
872  live_stack_->Reset();
873  STLDeleteValues(&mod_union_tables_);
874  STLDeleteValues(&remembered_sets_);
875  STLDeleteElements(&continuous_spaces_);
876  STLDeleteElements(&discontinuous_spaces_);
877  delete gc_complete_lock_;
878  delete heap_trim_request_lock_;
879  VLOG(heap) << "Finished ~Heap()";
880}
881
882space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
883                                                            bool fail_ok) const {
884  for (const auto& space : continuous_spaces_) {
885    if (space->Contains(obj)) {
886      return space;
887    }
888  }
889  if (!fail_ok) {
890    LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
891  }
892  return NULL;
893}
894
895space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
896                                                                  bool fail_ok) const {
897  for (const auto& space : discontinuous_spaces_) {
898    if (space->Contains(obj)) {
899      return space;
900    }
901  }
902  if (!fail_ok) {
903    LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
904  }
905  return NULL;
906}
907
908space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
909  space::Space* result = FindContinuousSpaceFromObject(obj, true);
910  if (result != NULL) {
911    return result;
912  }
913  return FindDiscontinuousSpaceFromObject(obj, true);
914}
915
916space::ImageSpace* Heap::GetImageSpace() const {
917  for (const auto& space : continuous_spaces_) {
918    if (space->IsImageSpace()) {
919      return space->AsImageSpace();
920    }
921  }
922  return NULL;
923}
924
925void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, AllocatorType allocator_type) {
926  std::ostringstream oss;
927  size_t total_bytes_free = GetFreeMemory();
928  oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
929      << " free bytes and " << PrettySize(GetFreeMemoryUntilOOME()) << " until OOM";
930  // If the allocation failed due to fragmentation, print out the largest continuous allocation.
931  if (total_bytes_free >= byte_count) {
932    space::AllocSpace* space = nullptr;
933    if (allocator_type == kAllocatorTypeNonMoving) {
934      space = non_moving_space_;
935    } else if (allocator_type == kAllocatorTypeRosAlloc ||
936               allocator_type == kAllocatorTypeDlMalloc) {
937      space = main_space_;
938    } else if (allocator_type == kAllocatorTypeBumpPointer ||
939               allocator_type == kAllocatorTypeTLAB) {
940      space = bump_pointer_space_;
941    }
942    if (space != nullptr) {
943      space->LogFragmentationAllocFailure(oss, byte_count);
944    }
945  }
946  self->ThrowOutOfMemoryError(oss.str().c_str());
947}
948
949void Heap::DoPendingTransitionOrTrim() {
950  Thread* self = Thread::Current();
951  CollectorType desired_collector_type;
952  // Wait until we reach the desired transition time.
953  while (true) {
954    uint64_t wait_time;
955    {
956      MutexLock mu(self, *heap_trim_request_lock_);
957      desired_collector_type = desired_collector_type_;
958      uint64_t current_time = NanoTime();
959      if (current_time >= heap_transition_or_trim_target_time_) {
960        break;
961      }
962      wait_time = heap_transition_or_trim_target_time_ - current_time;
963    }
964    ScopedThreadStateChange tsc(self, kSleeping);
965    usleep(wait_time / 1000);  // Usleep takes microseconds.
966  }
967  // Launch homogeneous space compaction if it is desired.
968  if (desired_collector_type == kCollectorTypeHomogeneousSpaceCompact) {
969    if (!CareAboutPauseTimes()) {
970      PerformHomogeneousSpaceCompact();
971    }
972    // No need to Trim(). Homogeneous space compaction may free more virtual and physical memory.
973    desired_collector_type = collector_type_;
974    return;
975  }
976  // Transition the collector if the desired collector type is not the same as the current
977  // collector type.
978  TransitionCollector(desired_collector_type);
979  if (!CareAboutPauseTimes()) {
980    // Deflate the monitors, this can cause a pause but shouldn't matter since we don't care
981    // about pauses.
982    Runtime* runtime = Runtime::Current();
983    runtime->GetThreadList()->SuspendAll();
984    uint64_t start_time = NanoTime();
985    size_t count = runtime->GetMonitorList()->DeflateMonitors();
986    VLOG(heap) << "Deflating " << count << " monitors took "
987        << PrettyDuration(NanoTime() - start_time);
988    runtime->GetThreadList()->ResumeAll();
989  }
990  // Do a heap trim if it is needed.
991  Trim();
992}
993
994void Heap::Trim() {
995  Thread* self = Thread::Current();
996  {
997    MutexLock mu(self, *heap_trim_request_lock_);
998    if (!heap_trim_request_pending_ || last_trim_time_ + kHeapTrimWait >= NanoTime()) {
999      return;
1000    }
1001    last_trim_time_ = NanoTime();
1002    heap_trim_request_pending_ = false;
1003  }
1004  {
1005    // Need to do this before acquiring the locks since we don't want to get suspended while
1006    // holding any locks.
1007    ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1008    // Pretend we are doing a GC to prevent background compaction from deleting the space we are
1009    // trimming.
1010    MutexLock mu(self, *gc_complete_lock_);
1011    // Ensure there is only one GC at a time.
1012    WaitForGcToCompleteLocked(kGcCauseTrim, self);
1013    collector_type_running_ = kCollectorTypeHeapTrim;
1014  }
1015  uint64_t start_ns = NanoTime();
1016  // Trim the managed spaces.
1017  uint64_t total_alloc_space_allocated = 0;
1018  uint64_t total_alloc_space_size = 0;
1019  uint64_t managed_reclaimed = 0;
1020  for (const auto& space : continuous_spaces_) {
1021    if (space->IsMallocSpace()) {
1022      gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
1023      if (malloc_space->IsRosAllocSpace() || !CareAboutPauseTimes()) {
1024        // Don't trim dlmalloc spaces if we care about pauses since this can hold the space lock
1025        // for a long period of time.
1026        managed_reclaimed += malloc_space->Trim();
1027      }
1028      total_alloc_space_size += malloc_space->Size();
1029    }
1030  }
1031  total_alloc_space_allocated = GetBytesAllocated() - large_object_space_->GetBytesAllocated();
1032  if (bump_pointer_space_ != nullptr) {
1033    total_alloc_space_allocated -= bump_pointer_space_->Size();
1034  }
1035  const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
1036      static_cast<float>(total_alloc_space_size);
1037  uint64_t gc_heap_end_ns = NanoTime();
1038  // We never move things in the native heap, so we can finish the GC at this point.
1039  FinishGC(self, collector::kGcTypeNone);
1040  size_t native_reclaimed = 0;
1041  // Only trim the native heap if we don't care about pauses.
1042  if (!CareAboutPauseTimes()) {
1043#if defined(USE_DLMALLOC)
1044    // Trim the native heap.
1045    dlmalloc_trim(0);
1046    dlmalloc_inspect_all(DlmallocMadviseCallback, &native_reclaimed);
1047#elif defined(USE_JEMALLOC)
1048    // Jemalloc does it's own internal trimming.
1049#else
1050    UNIMPLEMENTED(WARNING) << "Add trimming support";
1051#endif
1052  }
1053  uint64_t end_ns = NanoTime();
1054  VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
1055      << ", advised=" << PrettySize(managed_reclaimed) << ") and native (duration="
1056      << PrettyDuration(end_ns - gc_heap_end_ns) << ", advised=" << PrettySize(native_reclaimed)
1057      << ") heaps. Managed heap utilization of " << static_cast<int>(100 * managed_utilization)
1058      << "%.";
1059}
1060
1061bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
1062  // Note: we deliberately don't take the lock here, and mustn't test anything that would require
1063  // taking the lock.
1064  if (obj == nullptr) {
1065    return true;
1066  }
1067  return IsAligned<kObjectAlignment>(obj) && FindSpaceFromObject(obj, true) != nullptr;
1068}
1069
1070bool Heap::IsNonDiscontinuousSpaceHeapAddress(const mirror::Object* obj) const {
1071  return FindContinuousSpaceFromObject(obj, true) != nullptr;
1072}
1073
1074bool Heap::IsValidContinuousSpaceObjectAddress(const mirror::Object* obj) const {
1075  if (obj == nullptr || !IsAligned<kObjectAlignment>(obj)) {
1076    return false;
1077  }
1078  for (const auto& space : continuous_spaces_) {
1079    if (space->HasAddress(obj)) {
1080      return true;
1081    }
1082  }
1083  return false;
1084}
1085
1086bool Heap::IsLiveObjectLocked(mirror::Object* obj, bool search_allocation_stack,
1087                              bool search_live_stack, bool sorted) {
1088  if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
1089    return false;
1090  }
1091  if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj)) {
1092    mirror::Class* klass = obj->GetClass<kVerifyNone>();
1093    if (obj == klass) {
1094      // This case happens for java.lang.Class.
1095      return true;
1096    }
1097    return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
1098  } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj)) {
1099    // If we are in the allocated region of the temp space, then we are probably live (e.g. during
1100    // a GC). When a GC isn't running End() - Begin() is 0 which means no objects are contained.
1101    return temp_space_->Contains(obj);
1102  }
1103  space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
1104  space::DiscontinuousSpace* d_space = nullptr;
1105  if (c_space != nullptr) {
1106    if (c_space->GetLiveBitmap()->Test(obj)) {
1107      return true;
1108    }
1109  } else {
1110    d_space = FindDiscontinuousSpaceFromObject(obj, true);
1111    if (d_space != nullptr) {
1112      if (d_space->GetLiveBitmap()->Test(obj)) {
1113        return true;
1114      }
1115    }
1116  }
1117  // This is covering the allocation/live stack swapping that is done without mutators suspended.
1118  for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
1119    if (i > 0) {
1120      NanoSleep(MsToNs(10));
1121    }
1122    if (search_allocation_stack) {
1123      if (sorted) {
1124        if (allocation_stack_->ContainsSorted(obj)) {
1125          return true;
1126        }
1127      } else if (allocation_stack_->Contains(obj)) {
1128        return true;
1129      }
1130    }
1131
1132    if (search_live_stack) {
1133      if (sorted) {
1134        if (live_stack_->ContainsSorted(obj)) {
1135          return true;
1136        }
1137      } else if (live_stack_->Contains(obj)) {
1138        return true;
1139      }
1140    }
1141  }
1142  // We need to check the bitmaps again since there is a race where we mark something as live and
1143  // then clear the stack containing it.
1144  if (c_space != nullptr) {
1145    if (c_space->GetLiveBitmap()->Test(obj)) {
1146      return true;
1147    }
1148  } else {
1149    d_space = FindDiscontinuousSpaceFromObject(obj, true);
1150    if (d_space != nullptr && d_space->GetLiveBitmap()->Test(obj)) {
1151      return true;
1152    }
1153  }
1154  return false;
1155}
1156
1157std::string Heap::DumpSpaces() const {
1158  std::ostringstream oss;
1159  DumpSpaces(oss);
1160  return oss.str();
1161}
1162
1163void Heap::DumpSpaces(std::ostream& stream) const {
1164  for (const auto& space : continuous_spaces_) {
1165    accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1166    accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1167    stream << space << " " << *space << "\n";
1168    if (live_bitmap != nullptr) {
1169      stream << live_bitmap << " " << *live_bitmap << "\n";
1170    }
1171    if (mark_bitmap != nullptr) {
1172      stream << mark_bitmap << " " << *mark_bitmap << "\n";
1173    }
1174  }
1175  for (const auto& space : discontinuous_spaces_) {
1176    stream << space << " " << *space << "\n";
1177  }
1178}
1179
1180void Heap::VerifyObjectBody(mirror::Object* obj) {
1181  if (verify_object_mode_ == kVerifyObjectModeDisabled) {
1182    return;
1183  }
1184
1185  // Ignore early dawn of the universe verifications.
1186  if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.LoadRelaxed()) < 10 * KB)) {
1187    return;
1188  }
1189  CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
1190  mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(mirror::Object::ClassOffset());
1191  CHECK(c != nullptr) << "Null class in object " << obj;
1192  CHECK(IsAligned<kObjectAlignment>(c)) << "Class " << c << " not aligned in object " << obj;
1193  CHECK(VerifyClassClass(c));
1194
1195  if (verify_object_mode_ > kVerifyObjectModeFast) {
1196    // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
1197    CHECK(IsLiveObjectLocked(obj)) << "Object is dead " << obj << "\n" << DumpSpaces();
1198  }
1199}
1200
1201void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
1202  reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
1203}
1204
1205void Heap::VerifyHeap() {
1206  ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1207  GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
1208}
1209
1210void Heap::RecordFree(uint64_t freed_objects, int64_t freed_bytes) {
1211  // Use signed comparison since freed bytes can be negative when background compaction foreground
1212  // transitions occurs. This is caused by the moving objects from a bump pointer space to a
1213  // free list backed space typically increasing memory footprint due to padding and binning.
1214  DCHECK_LE(freed_bytes, static_cast<int64_t>(num_bytes_allocated_.LoadRelaxed()));
1215  // Note: This relies on 2s complement for handling negative freed_bytes.
1216  num_bytes_allocated_.FetchAndSubSequentiallyConsistent(static_cast<ssize_t>(freed_bytes));
1217  if (Runtime::Current()->HasStatsEnabled()) {
1218    RuntimeStats* thread_stats = Thread::Current()->GetStats();
1219    thread_stats->freed_objects += freed_objects;
1220    thread_stats->freed_bytes += freed_bytes;
1221    // TODO: Do this concurrently.
1222    RuntimeStats* global_stats = Runtime::Current()->GetStats();
1223    global_stats->freed_objects += freed_objects;
1224    global_stats->freed_bytes += freed_bytes;
1225  }
1226}
1227
1228space::RosAllocSpace* Heap::GetRosAllocSpace(gc::allocator::RosAlloc* rosalloc) const {
1229  for (const auto& space : continuous_spaces_) {
1230    if (space->AsContinuousSpace()->IsRosAllocSpace()) {
1231      if (space->AsContinuousSpace()->AsRosAllocSpace()->GetRosAlloc() == rosalloc) {
1232        return space->AsContinuousSpace()->AsRosAllocSpace();
1233      }
1234    }
1235  }
1236  return nullptr;
1237}
1238
1239mirror::Object* Heap::AllocateInternalWithGc(Thread* self, AllocatorType allocator,
1240                                             size_t alloc_size, size_t* bytes_allocated,
1241                                             size_t* usable_size,
1242                                             mirror::Class** klass) {
1243  bool was_default_allocator = allocator == GetCurrentAllocator();
1244  // Make sure there is no pending exception since we may need to throw an OOME.
1245  self->AssertNoPendingException();
1246  DCHECK(klass != nullptr);
1247  StackHandleScope<1> hs(self);
1248  HandleWrapper<mirror::Class> h(hs.NewHandleWrapper(klass));
1249  klass = nullptr;  // Invalidate for safety.
1250  // The allocation failed. If the GC is running, block until it completes, and then retry the
1251  // allocation.
1252  collector::GcType last_gc = WaitForGcToComplete(kGcCauseForAlloc, self);
1253  if (last_gc != collector::kGcTypeNone) {
1254    // If we were the default allocator but the allocator changed while we were suspended,
1255    // abort the allocation.
1256    if (was_default_allocator && allocator != GetCurrentAllocator()) {
1257      return nullptr;
1258    }
1259    // A GC was in progress and we blocked, retry allocation now that memory has been freed.
1260    mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
1261                                                     usable_size);
1262    if (ptr != nullptr) {
1263      return ptr;
1264    }
1265  }
1266
1267  collector::GcType tried_type = next_gc_type_;
1268  const bool gc_ran =
1269      CollectGarbageInternal(tried_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1270  if (was_default_allocator && allocator != GetCurrentAllocator()) {
1271    return nullptr;
1272  }
1273  if (gc_ran) {
1274    mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
1275                                                     usable_size);
1276    if (ptr != nullptr) {
1277      return ptr;
1278    }
1279  }
1280
1281  // Loop through our different Gc types and try to Gc until we get enough free memory.
1282  for (collector::GcType gc_type : gc_plan_) {
1283    if (gc_type == tried_type) {
1284      continue;
1285    }
1286    // Attempt to run the collector, if we succeed, re-try the allocation.
1287    const bool gc_ran =
1288        CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1289    if (was_default_allocator && allocator != GetCurrentAllocator()) {
1290      return nullptr;
1291    }
1292    if (gc_ran) {
1293      // Did we free sufficient memory for the allocation to succeed?
1294      mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
1295                                                       usable_size);
1296      if (ptr != nullptr) {
1297        return ptr;
1298      }
1299    }
1300  }
1301  // Allocations have failed after GCs;  this is an exceptional state.
1302  // Try harder, growing the heap if necessary.
1303  mirror::Object* ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
1304                                                  usable_size);
1305  if (ptr != nullptr) {
1306    return ptr;
1307  }
1308  // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1309  // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1310  // VM spec requires that all SoftReferences have been collected and cleared before throwing
1311  // OOME.
1312  VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1313           << " allocation";
1314  // TODO: Run finalization, but this may cause more allocations to occur.
1315  // We don't need a WaitForGcToComplete here either.
1316  DCHECK(!gc_plan_.empty());
1317  CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
1318  if (was_default_allocator && allocator != GetCurrentAllocator()) {
1319    return nullptr;
1320  }
1321  ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size);
1322  if (ptr == nullptr) {
1323    const uint64_t current_time = NanoTime();
1324    switch (allocator) {
1325      case kAllocatorTypeRosAlloc:
1326        // Fall-through.
1327      case kAllocatorTypeDlMalloc: {
1328        if (use_homogeneous_space_compaction_for_oom_ &&
1329            current_time - last_time_homogeneous_space_compaction_by_oom_ >
1330            min_interval_homogeneous_space_compaction_by_oom_) {
1331          last_time_homogeneous_space_compaction_by_oom_ = current_time;
1332          HomogeneousSpaceCompactResult result = PerformHomogeneousSpaceCompact();
1333          switch (result) {
1334            case HomogeneousSpaceCompactResult::kSuccess:
1335              // If the allocation succeeded, we delayed an oom.
1336              ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
1337                                              usable_size);
1338              if (ptr != nullptr) {
1339                count_delayed_oom_++;
1340              }
1341              break;
1342            case HomogeneousSpaceCompactResult::kErrorReject:
1343              // Reject due to disabled moving GC.
1344              break;
1345            case HomogeneousSpaceCompactResult::kErrorVMShuttingDown:
1346              // Throw OOM by default.
1347              break;
1348            default: {
1349              LOG(FATAL) << "Unimplemented homogeneous space compaction result "
1350                         << static_cast<size_t>(result);
1351            }
1352          }
1353          // Always print that we ran homogeneous space compation since this can cause jank.
1354          VLOG(heap) << "Ran heap homogeneous space compaction, "
1355                    << " requested defragmentation "
1356                    << count_requested_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1357                    << " performed defragmentation "
1358                    << count_performed_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1359                    << " ignored homogeneous space compaction "
1360                    << count_ignored_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1361                    << " delayed count = "
1362                    << count_delayed_oom_.LoadSequentiallyConsistent();
1363        }
1364        break;
1365      }
1366      case kAllocatorTypeNonMoving: {
1367        // Try to transition the heap if the allocation failure was due to the space being full.
1368        if (!IsOutOfMemoryOnAllocation<false>(allocator, alloc_size)) {
1369          // If we aren't out of memory then the OOM was probably from the non moving space being
1370          // full. Attempt to disable compaction and turn the main space into a non moving space.
1371          DisableMovingGc();
1372          // If we are still a moving GC then something must have caused the transition to fail.
1373          if (IsMovingGc(collector_type_)) {
1374            MutexLock mu(self, *gc_complete_lock_);
1375            // If we couldn't disable moving GC, just throw OOME and return null.
1376            LOG(WARNING) << "Couldn't disable moving GC with disable GC count "
1377                         << disable_moving_gc_count_;
1378          } else {
1379            LOG(WARNING) << "Disabled moving GC due to the non moving space being full";
1380            ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
1381                                            usable_size);
1382          }
1383        }
1384        break;
1385      }
1386      default: {
1387        // Do nothing for others allocators.
1388      }
1389    }
1390  }
1391  // If the allocation hasn't succeeded by this point, throw an OOM error.
1392  if (ptr == nullptr) {
1393    ThrowOutOfMemoryError(self, alloc_size, allocator);
1394  }
1395  return ptr;
1396}
1397
1398void Heap::SetTargetHeapUtilization(float target) {
1399  DCHECK_GT(target, 0.0f);  // asserted in Java code
1400  DCHECK_LT(target, 1.0f);
1401  target_utilization_ = target;
1402}
1403
1404size_t Heap::GetObjectsAllocated() const {
1405  size_t total = 0;
1406  for (space::AllocSpace* space : alloc_spaces_) {
1407    total += space->GetObjectsAllocated();
1408  }
1409  return total;
1410}
1411
1412uint64_t Heap::GetObjectsAllocatedEver() const {
1413  return GetObjectsFreedEver() + GetObjectsAllocated();
1414}
1415
1416uint64_t Heap::GetBytesAllocatedEver() const {
1417  return GetBytesFreedEver() + GetBytesAllocated();
1418}
1419
1420class InstanceCounter {
1421 public:
1422  InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
1423      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1424      : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
1425  }
1426  static void Callback(mirror::Object* obj, void* arg)
1427      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1428    InstanceCounter* instance_counter = reinterpret_cast<InstanceCounter*>(arg);
1429    mirror::Class* instance_class = obj->GetClass();
1430    CHECK(instance_class != nullptr);
1431    for (size_t i = 0; i < instance_counter->classes_.size(); ++i) {
1432      if (instance_counter->use_is_assignable_from_) {
1433        if (instance_counter->classes_[i]->IsAssignableFrom(instance_class)) {
1434          ++instance_counter->counts_[i];
1435        }
1436      } else if (instance_class == instance_counter->classes_[i]) {
1437        ++instance_counter->counts_[i];
1438      }
1439    }
1440  }
1441
1442 private:
1443  const std::vector<mirror::Class*>& classes_;
1444  bool use_is_assignable_from_;
1445  uint64_t* const counts_;
1446  DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
1447};
1448
1449void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
1450                          uint64_t* counts) {
1451  // Can't do any GC in this function since this may move classes.
1452  Thread* self = Thread::Current();
1453  auto* old_cause = self->StartAssertNoThreadSuspension("CountInstances");
1454  InstanceCounter counter(classes, use_is_assignable_from, counts);
1455  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1456  VisitObjects(InstanceCounter::Callback, &counter);
1457  self->EndAssertNoThreadSuspension(old_cause);
1458}
1459
1460class InstanceCollector {
1461 public:
1462  InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
1463      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1464      : class_(c), max_count_(max_count), instances_(instances) {
1465  }
1466  static void Callback(mirror::Object* obj, void* arg)
1467      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1468    DCHECK(arg != nullptr);
1469    InstanceCollector* instance_collector = reinterpret_cast<InstanceCollector*>(arg);
1470    mirror::Class* instance_class = obj->GetClass();
1471    if (instance_class == instance_collector->class_) {
1472      if (instance_collector->max_count_ == 0 ||
1473          instance_collector->instances_.size() < instance_collector->max_count_) {
1474        instance_collector->instances_.push_back(obj);
1475      }
1476    }
1477  }
1478
1479 private:
1480  mirror::Class* class_;
1481  uint32_t max_count_;
1482  std::vector<mirror::Object*>& instances_;
1483  DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1484};
1485
1486void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1487                        std::vector<mirror::Object*>& instances) {
1488  // Can't do any GC in this function since this may move classes.
1489  Thread* self = Thread::Current();
1490  auto* old_cause = self->StartAssertNoThreadSuspension("GetInstances");
1491  InstanceCollector collector(c, max_count, instances);
1492  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1493  VisitObjects(&InstanceCollector::Callback, &collector);
1494  self->EndAssertNoThreadSuspension(old_cause);
1495}
1496
1497class ReferringObjectsFinder {
1498 public:
1499  ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1500                         std::vector<mirror::Object*>& referring_objects)
1501      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1502      : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1503  }
1504
1505  static void Callback(mirror::Object* obj, void* arg)
1506      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1507    reinterpret_cast<ReferringObjectsFinder*>(arg)->operator()(obj);
1508  }
1509
1510  // For bitmap Visit.
1511  // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1512  // annotalysis on visitors.
1513  void operator()(mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
1514    o->VisitReferences<true>(*this, VoidFunctor());
1515  }
1516
1517  // For Object::VisitReferences.
1518  void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
1519      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1520    mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
1521    if (ref == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
1522      referring_objects_.push_back(obj);
1523    }
1524  }
1525
1526 private:
1527  mirror::Object* object_;
1528  uint32_t max_count_;
1529  std::vector<mirror::Object*>& referring_objects_;
1530  DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1531};
1532
1533void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1534                               std::vector<mirror::Object*>& referring_objects) {
1535  // Can't do any GC in this function since this may move the object o.
1536  Thread* self = Thread::Current();
1537  auto* old_cause = self->StartAssertNoThreadSuspension("GetReferringObjects");
1538  ReferringObjectsFinder finder(o, max_count, referring_objects);
1539  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1540  VisitObjects(&ReferringObjectsFinder::Callback, &finder);
1541  self->EndAssertNoThreadSuspension(old_cause);
1542}
1543
1544void Heap::CollectGarbage(bool clear_soft_references) {
1545  // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1546  // last GC will not have necessarily been cleared.
1547  CollectGarbageInternal(gc_plan_.back(), kGcCauseExplicit, clear_soft_references);
1548}
1549
1550HomogeneousSpaceCompactResult Heap::PerformHomogeneousSpaceCompact() {
1551  Thread* self = Thread::Current();
1552  // Inc requested homogeneous space compaction.
1553  count_requested_homogeneous_space_compaction_++;
1554  // Store performed homogeneous space compaction at a new request arrival.
1555  ThreadList* tl = Runtime::Current()->GetThreadList();
1556  ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1557  Locks::mutator_lock_->AssertNotHeld(self);
1558  {
1559    ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1560    MutexLock mu(self, *gc_complete_lock_);
1561    // Ensure there is only one GC at a time.
1562    WaitForGcToCompleteLocked(kGcCauseHomogeneousSpaceCompact, self);
1563    // Homogeneous space compaction is a copying transition, can't run it if the moving GC disable count
1564    // is non zero.
1565    // If the collector type changed to something which doesn't benefit from homogeneous space compaction,
1566    // exit.
1567    if (disable_moving_gc_count_ != 0 || IsMovingGc(collector_type_) ||
1568        !main_space_->CanMoveObjects()) {
1569      return HomogeneousSpaceCompactResult::kErrorReject;
1570    }
1571    collector_type_running_ = kCollectorTypeHomogeneousSpaceCompact;
1572  }
1573  if (Runtime::Current()->IsShuttingDown(self)) {
1574    // Don't allow heap transitions to happen if the runtime is shutting down since these can
1575    // cause objects to get finalized.
1576    FinishGC(self, collector::kGcTypeNone);
1577    return HomogeneousSpaceCompactResult::kErrorVMShuttingDown;
1578  }
1579  // Suspend all threads.
1580  tl->SuspendAll();
1581  uint64_t start_time = NanoTime();
1582  // Launch compaction.
1583  space::MallocSpace* to_space = main_space_backup_.release();
1584  space::MallocSpace* from_space = main_space_;
1585  to_space->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1586  const uint64_t space_size_before_compaction = from_space->Size();
1587  AddSpace(to_space);
1588  Compact(to_space, from_space, kGcCauseHomogeneousSpaceCompact);
1589  // Leave as prot read so that we can still run ROSAlloc verification on this space.
1590  from_space->GetMemMap()->Protect(PROT_READ);
1591  const uint64_t space_size_after_compaction = to_space->Size();
1592  main_space_ = to_space;
1593  main_space_backup_.reset(from_space);
1594  RemoveSpace(from_space);
1595  SetSpaceAsDefault(main_space_);  // Set as default to reset the proper dlmalloc space.
1596  // Update performed homogeneous space compaction count.
1597  count_performed_homogeneous_space_compaction_++;
1598  // Print statics log and resume all threads.
1599  uint64_t duration = NanoTime() - start_time;
1600  VLOG(heap) << "Heap homogeneous space compaction took " << PrettyDuration(duration) << " size: "
1601             << PrettySize(space_size_before_compaction) << " -> "
1602             << PrettySize(space_size_after_compaction) << " compact-ratio: "
1603             << std::fixed << static_cast<double>(space_size_after_compaction) /
1604             static_cast<double>(space_size_before_compaction);
1605  tl->ResumeAll();
1606  // Finish GC.
1607  reference_processor_.EnqueueClearedReferences(self);
1608  GrowForUtilization(semi_space_collector_);
1609  FinishGC(self, collector::kGcTypeFull);
1610  return HomogeneousSpaceCompactResult::kSuccess;
1611}
1612
1613
1614void Heap::TransitionCollector(CollectorType collector_type) {
1615  if (collector_type == collector_type_) {
1616    return;
1617  }
1618  VLOG(heap) << "TransitionCollector: " << static_cast<int>(collector_type_)
1619             << " -> " << static_cast<int>(collector_type);
1620  uint64_t start_time = NanoTime();
1621  uint32_t before_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
1622  Runtime* const runtime = Runtime::Current();
1623  ThreadList* const tl = runtime->GetThreadList();
1624  Thread* const self = Thread::Current();
1625  ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1626  Locks::mutator_lock_->AssertNotHeld(self);
1627  // Busy wait until we can GC (StartGC can fail if we have a non-zero
1628  // compacting_gc_disable_count_, this should rarely occurs).
1629  for (;;) {
1630    {
1631      ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1632      MutexLock mu(self, *gc_complete_lock_);
1633      // Ensure there is only one GC at a time.
1634      WaitForGcToCompleteLocked(kGcCauseCollectorTransition, self);
1635      // Currently we only need a heap transition if we switch from a moving collector to a
1636      // non-moving one, or visa versa.
1637      const bool copying_transition = IsMovingGc(collector_type_) != IsMovingGc(collector_type);
1638      // If someone else beat us to it and changed the collector before we could, exit.
1639      // This is safe to do before the suspend all since we set the collector_type_running_ before
1640      // we exit the loop. If another thread attempts to do the heap transition before we exit,
1641      // then it would get blocked on WaitForGcToCompleteLocked.
1642      if (collector_type == collector_type_) {
1643        return;
1644      }
1645      // GC can be disabled if someone has a used GetPrimitiveArrayCritical but not yet released.
1646      if (!copying_transition || disable_moving_gc_count_ == 0) {
1647        // TODO: Not hard code in semi-space collector?
1648        collector_type_running_ = copying_transition ? kCollectorTypeSS : collector_type;
1649        break;
1650      }
1651    }
1652    usleep(1000);
1653  }
1654  if (runtime->IsShuttingDown(self)) {
1655    // Don't allow heap transitions to happen if the runtime is shutting down since these can
1656    // cause objects to get finalized.
1657    FinishGC(self, collector::kGcTypeNone);
1658    return;
1659  }
1660  tl->SuspendAll();
1661  switch (collector_type) {
1662    case kCollectorTypeSS: {
1663      if (!IsMovingGc(collector_type_)) {
1664        // Create the bump pointer space from the backup space.
1665        CHECK(main_space_backup_ != nullptr);
1666        std::unique_ptr<MemMap> mem_map(main_space_backup_->ReleaseMemMap());
1667        // We are transitioning from non moving GC -> moving GC, since we copied from the bump
1668        // pointer space last transition it will be protected.
1669        CHECK(mem_map != nullptr);
1670        mem_map->Protect(PROT_READ | PROT_WRITE);
1671        bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space",
1672                                                                        mem_map.release());
1673        AddSpace(bump_pointer_space_);
1674        Compact(bump_pointer_space_, main_space_, kGcCauseCollectorTransition);
1675        // Use the now empty main space mem map for the bump pointer temp space.
1676        mem_map.reset(main_space_->ReleaseMemMap());
1677        // Unset the pointers just in case.
1678        if (dlmalloc_space_ == main_space_) {
1679          dlmalloc_space_ = nullptr;
1680        } else if (rosalloc_space_ == main_space_) {
1681          rosalloc_space_ = nullptr;
1682        }
1683        // Remove the main space so that we don't try to trim it, this doens't work for debug
1684        // builds since RosAlloc attempts to read the magic number from a protected page.
1685        RemoveSpace(main_space_);
1686        RemoveRememberedSet(main_space_);
1687        delete main_space_;  // Delete the space since it has been removed.
1688        main_space_ = nullptr;
1689        RemoveRememberedSet(main_space_backup_.get());
1690        main_space_backup_.reset(nullptr);  // Deletes the space.
1691        temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
1692                                                                mem_map.release());
1693        AddSpace(temp_space_);
1694      }
1695      break;
1696    }
1697    case kCollectorTypeMS:
1698      // Fall through.
1699    case kCollectorTypeCMS: {
1700      if (IsMovingGc(collector_type_)) {
1701        CHECK(temp_space_ != nullptr);
1702        std::unique_ptr<MemMap> mem_map(temp_space_->ReleaseMemMap());
1703        RemoveSpace(temp_space_);
1704        temp_space_ = nullptr;
1705        mem_map->Protect(PROT_READ | PROT_WRITE);
1706        CreateMainMallocSpace(mem_map.get(), kDefaultInitialSize, mem_map->Size(),
1707                              mem_map->Size());
1708        mem_map.release();
1709        // Compact to the main space from the bump pointer space, don't need to swap semispaces.
1710        AddSpace(main_space_);
1711        Compact(main_space_, bump_pointer_space_, kGcCauseCollectorTransition);
1712        mem_map.reset(bump_pointer_space_->ReleaseMemMap());
1713        RemoveSpace(bump_pointer_space_);
1714        bump_pointer_space_ = nullptr;
1715        const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
1716        // Temporarily unprotect the backup mem map so rosalloc can write the debug magic number.
1717        if (kIsDebugBuild && kUseRosAlloc) {
1718          mem_map->Protect(PROT_READ | PROT_WRITE);
1719        }
1720        main_space_backup_.reset(CreateMallocSpaceFromMemMap(mem_map.get(), kDefaultInitialSize,
1721                                                             mem_map->Size(), mem_map->Size(),
1722                                                             name, true));
1723        if (kIsDebugBuild && kUseRosAlloc) {
1724          mem_map->Protect(PROT_NONE);
1725        }
1726        mem_map.release();
1727      }
1728      break;
1729    }
1730    default: {
1731      LOG(FATAL) << "Attempted to transition to invalid collector type "
1732                 << static_cast<size_t>(collector_type);
1733      break;
1734    }
1735  }
1736  ChangeCollector(collector_type);
1737  tl->ResumeAll();
1738  // Can't call into java code with all threads suspended.
1739  reference_processor_.EnqueueClearedReferences(self);
1740  uint64_t duration = NanoTime() - start_time;
1741  GrowForUtilization(semi_space_collector_);
1742  FinishGC(self, collector::kGcTypeFull);
1743  int32_t after_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
1744  int32_t delta_allocated = before_allocated - after_allocated;
1745  std::string saved_str;
1746  if (delta_allocated >= 0) {
1747    saved_str = " saved at least " + PrettySize(delta_allocated);
1748  } else {
1749    saved_str = " expanded " + PrettySize(-delta_allocated);
1750  }
1751  VLOG(heap) << "Heap transition to " << process_state_ << " took "
1752      << PrettyDuration(duration) << saved_str;
1753}
1754
1755void Heap::ChangeCollector(CollectorType collector_type) {
1756  // TODO: Only do this with all mutators suspended to avoid races.
1757  if (collector_type != collector_type_) {
1758    if (collector_type == kCollectorTypeMC) {
1759      // Don't allow mark compact unless support is compiled in.
1760      CHECK(kMarkCompactSupport);
1761    }
1762    collector_type_ = collector_type;
1763    gc_plan_.clear();
1764    switch (collector_type_) {
1765      case kCollectorTypeCC:  // Fall-through.
1766      case kCollectorTypeMC:  // Fall-through.
1767      case kCollectorTypeSS:  // Fall-through.
1768      case kCollectorTypeGSS: {
1769        gc_plan_.push_back(collector::kGcTypeFull);
1770        if (use_tlab_) {
1771          ChangeAllocator(kAllocatorTypeTLAB);
1772        } else {
1773          ChangeAllocator(kAllocatorTypeBumpPointer);
1774        }
1775        break;
1776      }
1777      case kCollectorTypeMS: {
1778        gc_plan_.push_back(collector::kGcTypeSticky);
1779        gc_plan_.push_back(collector::kGcTypePartial);
1780        gc_plan_.push_back(collector::kGcTypeFull);
1781        ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
1782        break;
1783      }
1784      case kCollectorTypeCMS: {
1785        gc_plan_.push_back(collector::kGcTypeSticky);
1786        gc_plan_.push_back(collector::kGcTypePartial);
1787        gc_plan_.push_back(collector::kGcTypeFull);
1788        ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
1789        break;
1790      }
1791      default: {
1792        LOG(FATAL) << "Unimplemented";
1793      }
1794    }
1795    if (IsGcConcurrent()) {
1796      concurrent_start_bytes_ =
1797          std::max(max_allowed_footprint_, kMinConcurrentRemainingBytes) - kMinConcurrentRemainingBytes;
1798    } else {
1799      concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1800    }
1801  }
1802}
1803
1804// Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
1805class ZygoteCompactingCollector FINAL : public collector::SemiSpace {
1806 public:
1807  explicit ZygoteCompactingCollector(gc::Heap* heap) : SemiSpace(heap, false, "zygote collector"),
1808      bin_live_bitmap_(nullptr), bin_mark_bitmap_(nullptr) {
1809  }
1810
1811  void BuildBins(space::ContinuousSpace* space) {
1812    bin_live_bitmap_ = space->GetLiveBitmap();
1813    bin_mark_bitmap_ = space->GetMarkBitmap();
1814    BinContext context;
1815    context.prev_ = reinterpret_cast<uintptr_t>(space->Begin());
1816    context.collector_ = this;
1817    WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1818    // Note: This requires traversing the space in increasing order of object addresses.
1819    bin_live_bitmap_->Walk(Callback, reinterpret_cast<void*>(&context));
1820    // Add the last bin which spans after the last object to the end of the space.
1821    AddBin(reinterpret_cast<uintptr_t>(space->End()) - context.prev_, context.prev_);
1822  }
1823
1824 private:
1825  struct BinContext {
1826    uintptr_t prev_;  // The end of the previous object.
1827    ZygoteCompactingCollector* collector_;
1828  };
1829  // Maps from bin sizes to locations.
1830  std::multimap<size_t, uintptr_t> bins_;
1831  // Live bitmap of the space which contains the bins.
1832  accounting::ContinuousSpaceBitmap* bin_live_bitmap_;
1833  // Mark bitmap of the space which contains the bins.
1834  accounting::ContinuousSpaceBitmap* bin_mark_bitmap_;
1835
1836  static void Callback(mirror::Object* obj, void* arg)
1837      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1838    DCHECK(arg != nullptr);
1839    BinContext* context = reinterpret_cast<BinContext*>(arg);
1840    ZygoteCompactingCollector* collector = context->collector_;
1841    uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
1842    size_t bin_size = object_addr - context->prev_;
1843    // Add the bin consisting of the end of the previous object to the start of the current object.
1844    collector->AddBin(bin_size, context->prev_);
1845    context->prev_ = object_addr + RoundUp(obj->SizeOf(), kObjectAlignment);
1846  }
1847
1848  void AddBin(size_t size, uintptr_t position) {
1849    if (size != 0) {
1850      bins_.insert(std::make_pair(size, position));
1851    }
1852  }
1853
1854  virtual bool ShouldSweepSpace(space::ContinuousSpace* space) const {
1855    // Don't sweep any spaces since we probably blasted the internal accounting of the free list
1856    // allocator.
1857    return false;
1858  }
1859
1860  virtual mirror::Object* MarkNonForwardedObject(mirror::Object* obj)
1861      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
1862    size_t object_size = RoundUp(obj->SizeOf(), kObjectAlignment);
1863    mirror::Object* forward_address;
1864    // Find the smallest bin which we can move obj in.
1865    auto it = bins_.lower_bound(object_size);
1866    if (it == bins_.end()) {
1867      // No available space in the bins, place it in the target space instead (grows the zygote
1868      // space).
1869      size_t bytes_allocated;
1870      forward_address = to_space_->Alloc(self_, object_size, &bytes_allocated, nullptr);
1871      if (to_space_live_bitmap_ != nullptr) {
1872        to_space_live_bitmap_->Set(forward_address);
1873      } else {
1874        GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
1875        GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
1876      }
1877    } else {
1878      size_t size = it->first;
1879      uintptr_t pos = it->second;
1880      bins_.erase(it);  // Erase the old bin which we replace with the new smaller bin.
1881      forward_address = reinterpret_cast<mirror::Object*>(pos);
1882      // Set the live and mark bits so that sweeping system weaks works properly.
1883      bin_live_bitmap_->Set(forward_address);
1884      bin_mark_bitmap_->Set(forward_address);
1885      DCHECK_GE(size, object_size);
1886      AddBin(size - object_size, pos + object_size);  // Add a new bin with the remaining space.
1887    }
1888    // Copy the object over to its new location.
1889    memcpy(reinterpret_cast<void*>(forward_address), obj, object_size);
1890    if (kUseBakerOrBrooksReadBarrier) {
1891      obj->AssertReadBarrierPointer();
1892      if (kUseBrooksReadBarrier) {
1893        DCHECK_EQ(forward_address->GetReadBarrierPointer(), obj);
1894        forward_address->SetReadBarrierPointer(forward_address);
1895      }
1896      forward_address->AssertReadBarrierPointer();
1897    }
1898    return forward_address;
1899  }
1900};
1901
1902void Heap::UnBindBitmaps() {
1903  TimingLogger::ScopedTiming t("UnBindBitmaps", GetCurrentGcIteration()->GetTimings());
1904  for (const auto& space : GetContinuousSpaces()) {
1905    if (space->IsContinuousMemMapAllocSpace()) {
1906      space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1907      if (alloc_space->HasBoundBitmaps()) {
1908        alloc_space->UnBindBitmaps();
1909      }
1910    }
1911  }
1912}
1913
1914void Heap::PreZygoteFork() {
1915  CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
1916  Thread* self = Thread::Current();
1917  MutexLock mu(self, zygote_creation_lock_);
1918  // Try to see if we have any Zygote spaces.
1919  if (have_zygote_space_) {
1920    return;
1921  }
1922  Runtime::Current()->GetInternTable()->SwapPostZygoteWithPreZygote();
1923  Runtime::Current()->GetClassLinker()->MoveClassTableToPreZygote();
1924  VLOG(heap) << "Starting PreZygoteFork";
1925  // Trim the pages at the end of the non moving space.
1926  non_moving_space_->Trim();
1927  // The end of the non-moving space may be protected, unprotect it so that we can copy the zygote
1928  // there.
1929  non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1930  const bool same_space = non_moving_space_ == main_space_;
1931  if (kCompactZygote) {
1932    // Can't compact if the non moving space is the same as the main space.
1933    DCHECK(semi_space_collector_ != nullptr);
1934    // Temporarily disable rosalloc verification because the zygote
1935    // compaction will mess up the rosalloc internal metadata.
1936    ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
1937    ZygoteCompactingCollector zygote_collector(this);
1938    zygote_collector.BuildBins(non_moving_space_);
1939    // Create a new bump pointer space which we will compact into.
1940    space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
1941                                         non_moving_space_->Limit());
1942    // Compact the bump pointer space to a new zygote bump pointer space.
1943    bool reset_main_space = false;
1944    if (IsMovingGc(collector_type_)) {
1945      zygote_collector.SetFromSpace(bump_pointer_space_);
1946    } else {
1947      CHECK(main_space_ != nullptr);
1948      // Copy from the main space.
1949      zygote_collector.SetFromSpace(main_space_);
1950      reset_main_space = true;
1951    }
1952    zygote_collector.SetToSpace(&target_space);
1953    zygote_collector.SetSwapSemiSpaces(false);
1954    zygote_collector.Run(kGcCauseCollectorTransition, false);
1955    if (reset_main_space) {
1956      main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1957      madvise(main_space_->Begin(), main_space_->Capacity(), MADV_DONTNEED);
1958      MemMap* mem_map = main_space_->ReleaseMemMap();
1959      RemoveSpace(main_space_);
1960      space::Space* old_main_space = main_space_;
1961      CreateMainMallocSpace(mem_map, kDefaultInitialSize, mem_map->Size(), mem_map->Size());
1962      delete old_main_space;
1963      AddSpace(main_space_);
1964    } else {
1965      bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1966    }
1967    if (temp_space_ != nullptr) {
1968      CHECK(temp_space_->IsEmpty());
1969    }
1970    total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
1971    total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
1972    // Update the end and write out image.
1973    non_moving_space_->SetEnd(target_space.End());
1974    non_moving_space_->SetLimit(target_space.Limit());
1975    VLOG(heap) << "Zygote space size " << non_moving_space_->Size() << " bytes";
1976  }
1977  // Change the collector to the post zygote one.
1978  ChangeCollector(foreground_collector_type_);
1979  // Save the old space so that we can remove it after we complete creating the zygote space.
1980  space::MallocSpace* old_alloc_space = non_moving_space_;
1981  // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
1982  // the remaining available space.
1983  // Remove the old space before creating the zygote space since creating the zygote space sets
1984  // the old alloc space's bitmaps to nullptr.
1985  RemoveSpace(old_alloc_space);
1986  if (collector::SemiSpace::kUseRememberedSet) {
1987    // Sanity bound check.
1988    FindRememberedSetFromSpace(old_alloc_space)->AssertAllDirtyCardsAreWithinSpace();
1989    // Remove the remembered set for the now zygote space (the old
1990    // non-moving space). Note now that we have compacted objects into
1991    // the zygote space, the data in the remembered set is no longer
1992    // needed. The zygote space will instead have a mod-union table
1993    // from this point on.
1994    RemoveRememberedSet(old_alloc_space);
1995  }
1996  // Remaining space becomes the new non moving space.
1997  space::ZygoteSpace* zygote_space = old_alloc_space->CreateZygoteSpace(kNonMovingSpaceName,
1998                                                                        low_memory_mode_,
1999                                                                        &non_moving_space_);
2000  CHECK(!non_moving_space_->CanMoveObjects());
2001  if (same_space) {
2002    main_space_ = non_moving_space_;
2003    SetSpaceAsDefault(main_space_);
2004  }
2005  delete old_alloc_space;
2006  CHECK(zygote_space != nullptr) << "Failed creating zygote space";
2007  AddSpace(zygote_space);
2008  non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
2009  AddSpace(non_moving_space_);
2010  have_zygote_space_ = true;
2011  // Enable large object space allocations.
2012  large_object_threshold_ = kDefaultLargeObjectThreshold;
2013  // Create the zygote space mod union table.
2014  accounting::ModUnionTable* mod_union_table =
2015      new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space);
2016  CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
2017  AddModUnionTable(mod_union_table);
2018  if (collector::SemiSpace::kUseRememberedSet) {
2019    // Add a new remembered set for the post-zygote non-moving space.
2020    accounting::RememberedSet* post_zygote_non_moving_space_rem_set =
2021        new accounting::RememberedSet("Post-zygote non-moving space remembered set", this,
2022                                      non_moving_space_);
2023    CHECK(post_zygote_non_moving_space_rem_set != nullptr)
2024        << "Failed to create post-zygote non-moving space remembered set";
2025    AddRememberedSet(post_zygote_non_moving_space_rem_set);
2026  }
2027}
2028
2029void Heap::FlushAllocStack() {
2030  MarkAllocStackAsLive(allocation_stack_.get());
2031  allocation_stack_->Reset();
2032}
2033
2034void Heap::MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1,
2035                          accounting::ContinuousSpaceBitmap* bitmap2,
2036                          accounting::LargeObjectBitmap* large_objects,
2037                          accounting::ObjectStack* stack) {
2038  DCHECK(bitmap1 != nullptr);
2039  DCHECK(bitmap2 != nullptr);
2040  mirror::Object** limit = stack->End();
2041  for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
2042    const mirror::Object* obj = *it;
2043    if (!kUseThreadLocalAllocationStack || obj != nullptr) {
2044      if (bitmap1->HasAddress(obj)) {
2045        bitmap1->Set(obj);
2046      } else if (bitmap2->HasAddress(obj)) {
2047        bitmap2->Set(obj);
2048      } else {
2049        large_objects->Set(obj);
2050      }
2051    }
2052  }
2053}
2054
2055void Heap::SwapSemiSpaces() {
2056  CHECK(bump_pointer_space_ != nullptr);
2057  CHECK(temp_space_ != nullptr);
2058  std::swap(bump_pointer_space_, temp_space_);
2059}
2060
2061void Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
2062                   space::ContinuousMemMapAllocSpace* source_space,
2063                   GcCause gc_cause) {
2064  CHECK(kMovingCollector);
2065  if (target_space != source_space) {
2066    // Don't swap spaces since this isn't a typical semi space collection.
2067    semi_space_collector_->SetSwapSemiSpaces(false);
2068    semi_space_collector_->SetFromSpace(source_space);
2069    semi_space_collector_->SetToSpace(target_space);
2070    semi_space_collector_->Run(gc_cause, false);
2071  } else {
2072    CHECK(target_space->IsBumpPointerSpace())
2073        << "In-place compaction is only supported for bump pointer spaces";
2074    mark_compact_collector_->SetSpace(target_space->AsBumpPointerSpace());
2075    mark_compact_collector_->Run(kGcCauseCollectorTransition, false);
2076  }
2077}
2078
2079collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
2080                                               bool clear_soft_references) {
2081  Thread* self = Thread::Current();
2082  Runtime* runtime = Runtime::Current();
2083  // If the heap can't run the GC, silently fail and return that no GC was run.
2084  switch (gc_type) {
2085    case collector::kGcTypePartial: {
2086      if (!have_zygote_space_) {
2087        return collector::kGcTypeNone;
2088      }
2089      break;
2090    }
2091    default: {
2092      // Other GC types don't have any special cases which makes them not runnable. The main case
2093      // here is full GC.
2094    }
2095  }
2096  ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
2097  Locks::mutator_lock_->AssertNotHeld(self);
2098  if (self->IsHandlingStackOverflow()) {
2099    LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
2100  }
2101  bool compacting_gc;
2102  {
2103    gc_complete_lock_->AssertNotHeld(self);
2104    ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
2105    MutexLock mu(self, *gc_complete_lock_);
2106    // Ensure there is only one GC at a time.
2107    WaitForGcToCompleteLocked(gc_cause, self);
2108    compacting_gc = IsMovingGc(collector_type_);
2109    // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
2110    if (compacting_gc && disable_moving_gc_count_ != 0) {
2111      LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
2112      return collector::kGcTypeNone;
2113    }
2114    collector_type_running_ = collector_type_;
2115  }
2116
2117  if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
2118    ++runtime->GetStats()->gc_for_alloc_count;
2119    ++self->GetStats()->gc_for_alloc_count;
2120  }
2121  uint64_t gc_start_time_ns = NanoTime();
2122  uint64_t gc_start_size = GetBytesAllocated();
2123  // Approximate allocation rate in bytes / second.
2124  uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
2125  // Back to back GCs can cause 0 ms of wait time in between GC invocations.
2126  if (LIKELY(ms_delta != 0)) {
2127    allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
2128    ATRACE_INT("Allocation rate KB/s", allocation_rate_ / KB);
2129    VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
2130  }
2131
2132  DCHECK_LT(gc_type, collector::kGcTypeMax);
2133  DCHECK_NE(gc_type, collector::kGcTypeNone);
2134
2135  collector::GarbageCollector* collector = nullptr;
2136  // TODO: Clean this up.
2137  if (compacting_gc) {
2138    DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
2139           current_allocator_ == kAllocatorTypeTLAB);
2140    switch (collector_type_) {
2141      case kCollectorTypeSS:
2142        // Fall-through.
2143      case kCollectorTypeGSS:
2144        semi_space_collector_->SetFromSpace(bump_pointer_space_);
2145        semi_space_collector_->SetToSpace(temp_space_);
2146        semi_space_collector_->SetSwapSemiSpaces(true);
2147        collector = semi_space_collector_;
2148        break;
2149      case kCollectorTypeCC:
2150        collector = concurrent_copying_collector_;
2151        break;
2152      case kCollectorTypeMC:
2153        mark_compact_collector_->SetSpace(bump_pointer_space_);
2154        collector = mark_compact_collector_;
2155        break;
2156      default:
2157        LOG(FATAL) << "Invalid collector type " << static_cast<size_t>(collector_type_);
2158    }
2159    if (collector != mark_compact_collector_) {
2160      temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2161      CHECK(temp_space_->IsEmpty());
2162    }
2163    gc_type = collector::kGcTypeFull;  // TODO: Not hard code this in.
2164  } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
2165      current_allocator_ == kAllocatorTypeDlMalloc) {
2166    collector = FindCollectorByGcType(gc_type);
2167  } else {
2168    LOG(FATAL) << "Invalid current allocator " << current_allocator_;
2169  }
2170  if (IsGcConcurrent()) {
2171    // Disable concurrent GC check so that we don't have spammy JNI requests.
2172    // This gets recalculated in GrowForUtilization. It is important that it is disabled /
2173    // calculated in the same thread so that there aren't any races that can cause it to become
2174    // permanantly disabled. b/17942071
2175    concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
2176  }
2177  CHECK(collector != nullptr)
2178      << "Could not find garbage collector with collector_type="
2179      << static_cast<size_t>(collector_type_) << " and gc_type=" << gc_type;
2180  collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
2181  total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2182  total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
2183  RequestHeapTrim();
2184  // Enqueue cleared references.
2185  reference_processor_.EnqueueClearedReferences(self);
2186  // Grow the heap so that we know when to perform the next GC.
2187  GrowForUtilization(collector);
2188  const size_t duration = GetCurrentGcIteration()->GetDurationNs();
2189  const std::vector<uint64_t>& pause_times = GetCurrentGcIteration()->GetPauseTimes();
2190  // Print the GC if it is an explicit GC (e.g. Runtime.gc()) or a slow GC
2191  // (mutator time blocked >= long_pause_log_threshold_).
2192  bool log_gc = gc_cause == kGcCauseExplicit;
2193  if (!log_gc && CareAboutPauseTimes()) {
2194    // GC for alloc pauses the allocating thread, so consider it as a pause.
2195    log_gc = duration > long_gc_log_threshold_ ||
2196        (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
2197    for (uint64_t pause : pause_times) {
2198      log_gc = log_gc || pause >= long_pause_log_threshold_;
2199    }
2200  }
2201  if (log_gc) {
2202    const size_t percent_free = GetPercentFree();
2203    const size_t current_heap_size = GetBytesAllocated();
2204    const size_t total_memory = GetTotalMemory();
2205    std::ostringstream pause_string;
2206    for (size_t i = 0; i < pause_times.size(); ++i) {
2207        pause_string << PrettyDuration((pause_times[i] / 1000) * 1000)
2208                     << ((i != pause_times.size() - 1) ? "," : "");
2209    }
2210    LOG(INFO) << gc_cause << " " << collector->GetName()
2211              << " GC freed "  << current_gc_iteration_.GetFreedObjects() << "("
2212              << PrettySize(current_gc_iteration_.GetFreedBytes()) << ") AllocSpace objects, "
2213              << current_gc_iteration_.GetFreedLargeObjects() << "("
2214              << PrettySize(current_gc_iteration_.GetFreedLargeObjectBytes()) << ") LOS objects, "
2215              << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
2216              << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
2217              << " total " << PrettyDuration((duration / 1000) * 1000);
2218    VLOG(heap) << ConstDumpable<TimingLogger>(*current_gc_iteration_.GetTimings());
2219  }
2220  FinishGC(self, gc_type);
2221  // Inform DDMS that a GC completed.
2222  Dbg::GcDidFinish();
2223  return gc_type;
2224}
2225
2226void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
2227  MutexLock mu(self, *gc_complete_lock_);
2228  collector_type_running_ = kCollectorTypeNone;
2229  if (gc_type != collector::kGcTypeNone) {
2230    last_gc_type_ = gc_type;
2231  }
2232  // Wake anyone who may have been waiting for the GC to complete.
2233  gc_complete_cond_->Broadcast(self);
2234}
2235
2236static void RootMatchesObjectVisitor(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
2237                                     RootType /*root_type*/) {
2238  mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
2239  if (*root == obj) {
2240    LOG(INFO) << "Object " << obj << " is a root";
2241  }
2242}
2243
2244class ScanVisitor {
2245 public:
2246  void operator()(const mirror::Object* obj) const {
2247    LOG(ERROR) << "Would have rescanned object " << obj;
2248  }
2249};
2250
2251// Verify a reference from an object.
2252class VerifyReferenceVisitor {
2253 public:
2254  explicit VerifyReferenceVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
2255      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
2256      : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
2257
2258  size_t GetFailureCount() const {
2259    return fail_count_->LoadSequentiallyConsistent();
2260  }
2261
2262  void operator()(mirror::Class* klass, mirror::Reference* ref) const
2263      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2264    if (verify_referent_) {
2265      VerifyReference(ref, ref->GetReferent(), mirror::Reference::ReferentOffset());
2266    }
2267  }
2268
2269  void operator()(mirror::Object* obj, MemberOffset offset, bool /*is_static*/) const
2270      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2271    VerifyReference(obj, obj->GetFieldObject<mirror::Object>(offset), offset);
2272  }
2273
2274  bool IsLive(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
2275    return heap_->IsLiveObjectLocked(obj, true, false, true);
2276  }
2277
2278  static void VerifyRootCallback(mirror::Object** root, void* arg, uint32_t thread_id,
2279                                 RootType root_type) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2280    VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
2281    if (!visitor->VerifyReference(nullptr, *root, MemberOffset(0))) {
2282      LOG(ERROR) << "Root " << *root << " is dead with type " << PrettyTypeOf(*root)
2283          << " thread_id= " << thread_id << " root_type= " << root_type;
2284    }
2285  }
2286
2287 private:
2288  // TODO: Fix the no thread safety analysis.
2289  // Returns false on failure.
2290  bool VerifyReference(mirror::Object* obj, mirror::Object* ref, MemberOffset offset) const
2291      NO_THREAD_SAFETY_ANALYSIS {
2292    if (ref == nullptr || IsLive(ref)) {
2293      // Verify that the reference is live.
2294      return true;
2295    }
2296    if (fail_count_->FetchAndAddSequentiallyConsistent(1) == 0) {
2297      // Print message on only on first failure to prevent spam.
2298      LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
2299    }
2300    if (obj != nullptr) {
2301      // Only do this part for non roots.
2302      accounting::CardTable* card_table = heap_->GetCardTable();
2303      accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
2304      accounting::ObjectStack* live_stack = heap_->live_stack_.get();
2305      byte* card_addr = card_table->CardFromAddr(obj);
2306      LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
2307                 << offset << "\n card value = " << static_cast<int>(*card_addr);
2308      if (heap_->IsValidObjectAddress(obj->GetClass())) {
2309        LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
2310      } else {
2311        LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
2312      }
2313
2314      // Attempt to find the class inside of the recently freed objects.
2315      space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
2316      if (ref_space != nullptr && ref_space->IsMallocSpace()) {
2317        space::MallocSpace* space = ref_space->AsMallocSpace();
2318        mirror::Class* ref_class = space->FindRecentFreedObject(ref);
2319        if (ref_class != nullptr) {
2320          LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
2321                     << PrettyClass(ref_class);
2322        } else {
2323          LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
2324        }
2325      }
2326
2327      if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
2328          ref->GetClass()->IsClass()) {
2329        LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
2330      } else {
2331        LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
2332                   << ") is not a valid heap address";
2333      }
2334
2335      card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
2336      void* cover_begin = card_table->AddrFromCard(card_addr);
2337      void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
2338          accounting::CardTable::kCardSize);
2339      LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
2340          << "-" << cover_end;
2341      accounting::ContinuousSpaceBitmap* bitmap =
2342          heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
2343
2344      if (bitmap == nullptr) {
2345        LOG(ERROR) << "Object " << obj << " has no bitmap";
2346        if (!VerifyClassClass(obj->GetClass())) {
2347          LOG(ERROR) << "Object " << obj << " failed class verification!";
2348        }
2349      } else {
2350        // Print out how the object is live.
2351        if (bitmap->Test(obj)) {
2352          LOG(ERROR) << "Object " << obj << " found in live bitmap";
2353        }
2354        if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
2355          LOG(ERROR) << "Object " << obj << " found in allocation stack";
2356        }
2357        if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
2358          LOG(ERROR) << "Object " << obj << " found in live stack";
2359        }
2360        if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
2361          LOG(ERROR) << "Ref " << ref << " found in allocation stack";
2362        }
2363        if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
2364          LOG(ERROR) << "Ref " << ref << " found in live stack";
2365        }
2366        // Attempt to see if the card table missed the reference.
2367        ScanVisitor scan_visitor;
2368        byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
2369        card_table->Scan(bitmap, byte_cover_begin,
2370                         byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
2371      }
2372
2373      // Search to see if any of the roots reference our object.
2374      void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
2375      Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg);
2376
2377      // Search to see if any of the roots reference our reference.
2378      arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
2379      Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg);
2380    }
2381    return false;
2382  }
2383
2384  Heap* const heap_;
2385  Atomic<size_t>* const fail_count_;
2386  const bool verify_referent_;
2387};
2388
2389// Verify all references within an object, for use with HeapBitmap::Visit.
2390class VerifyObjectVisitor {
2391 public:
2392  explicit VerifyObjectVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
2393      : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {
2394  }
2395
2396  void operator()(mirror::Object* obj) const
2397      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2398    // Note: we are verifying the references in obj but not obj itself, this is because obj must
2399    // be live or else how did we find it in the live bitmap?
2400    VerifyReferenceVisitor visitor(heap_, fail_count_, verify_referent_);
2401    // The class doesn't count as a reference but we should verify it anyways.
2402    obj->VisitReferences<true>(visitor, visitor);
2403  }
2404
2405  static void VisitCallback(mirror::Object* obj, void* arg)
2406      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2407    VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
2408    visitor->operator()(obj);
2409  }
2410
2411  size_t GetFailureCount() const {
2412    return fail_count_->LoadSequentiallyConsistent();
2413  }
2414
2415 private:
2416  Heap* const heap_;
2417  Atomic<size_t>* const fail_count_;
2418  const bool verify_referent_;
2419};
2420
2421void Heap::PushOnAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2422  // Slow path, the allocation stack push back must have already failed.
2423  DCHECK(!allocation_stack_->AtomicPushBack(*obj));
2424  do {
2425    // TODO: Add handle VerifyObject.
2426    StackHandleScope<1> hs(self);
2427    HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2428    // Push our object into the reserve region of the allocaiton stack. This is only required due
2429    // to heap verification requiring that roots are live (either in the live bitmap or in the
2430    // allocation stack).
2431    CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2432    CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2433  } while (!allocation_stack_->AtomicPushBack(*obj));
2434}
2435
2436void Heap::PushOnThreadLocalAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2437  // Slow path, the allocation stack push back must have already failed.
2438  DCHECK(!self->PushOnThreadLocalAllocationStack(*obj));
2439  mirror::Object** start_address;
2440  mirror::Object** end_address;
2441  while (!allocation_stack_->AtomicBumpBack(kThreadLocalAllocationStackSize, &start_address,
2442                                            &end_address)) {
2443    // TODO: Add handle VerifyObject.
2444    StackHandleScope<1> hs(self);
2445    HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2446    // Push our object into the reserve region of the allocaiton stack. This is only required due
2447    // to heap verification requiring that roots are live (either in the live bitmap or in the
2448    // allocation stack).
2449    CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2450    // Push into the reserve allocation stack.
2451    CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2452  }
2453  self->SetThreadLocalAllocationStack(start_address, end_address);
2454  // Retry on the new thread-local allocation stack.
2455  CHECK(self->PushOnThreadLocalAllocationStack(*obj));  // Must succeed.
2456}
2457
2458// Must do this with mutators suspended since we are directly accessing the allocation stacks.
2459size_t Heap::VerifyHeapReferences(bool verify_referents) {
2460  Thread* self = Thread::Current();
2461  Locks::mutator_lock_->AssertExclusiveHeld(self);
2462  // Lets sort our allocation stacks so that we can efficiently binary search them.
2463  allocation_stack_->Sort();
2464  live_stack_->Sort();
2465  // Since we sorted the allocation stack content, need to revoke all
2466  // thread-local allocation stacks.
2467  RevokeAllThreadLocalAllocationStacks(self);
2468  Atomic<size_t> fail_count_(0);
2469  VerifyObjectVisitor visitor(this, &fail_count_, verify_referents);
2470  // Verify objects in the allocation stack since these will be objects which were:
2471  // 1. Allocated prior to the GC (pre GC verification).
2472  // 2. Allocated during the GC (pre sweep GC verification).
2473  // We don't want to verify the objects in the live stack since they themselves may be
2474  // pointing to dead objects if they are not reachable.
2475  VisitObjects(VerifyObjectVisitor::VisitCallback, &visitor);
2476  // Verify the roots:
2477  Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRootCallback, &visitor);
2478  if (visitor.GetFailureCount() > 0) {
2479    // Dump mod-union tables.
2480    for (const auto& table_pair : mod_union_tables_) {
2481      accounting::ModUnionTable* mod_union_table = table_pair.second;
2482      mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
2483    }
2484    // Dump remembered sets.
2485    for (const auto& table_pair : remembered_sets_) {
2486      accounting::RememberedSet* remembered_set = table_pair.second;
2487      remembered_set->Dump(LOG(ERROR) << remembered_set->GetName() << ": ");
2488    }
2489    DumpSpaces(LOG(ERROR));
2490  }
2491  return visitor.GetFailureCount();
2492}
2493
2494class VerifyReferenceCardVisitor {
2495 public:
2496  VerifyReferenceCardVisitor(Heap* heap, bool* failed)
2497      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
2498                            Locks::heap_bitmap_lock_)
2499      : heap_(heap), failed_(failed) {
2500  }
2501
2502  // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
2503  // annotalysis on visitors.
2504  void operator()(mirror::Object* obj, MemberOffset offset, bool is_static) const
2505      NO_THREAD_SAFETY_ANALYSIS {
2506    mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
2507    // Filter out class references since changing an object's class does not mark the card as dirty.
2508    // Also handles large objects, since the only reference they hold is a class reference.
2509    if (ref != nullptr && !ref->IsClass()) {
2510      accounting::CardTable* card_table = heap_->GetCardTable();
2511      // If the object is not dirty and it is referencing something in the live stack other than
2512      // class, then it must be on a dirty card.
2513      if (!card_table->AddrIsInCardTable(obj)) {
2514        LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
2515        *failed_ = true;
2516      } else if (!card_table->IsDirty(obj)) {
2517        // TODO: Check mod-union tables.
2518        // Card should be either kCardDirty if it got re-dirtied after we aged it, or
2519        // kCardDirty - 1 if it didnt get touched since we aged it.
2520        accounting::ObjectStack* live_stack = heap_->live_stack_.get();
2521        if (live_stack->ContainsSorted(ref)) {
2522          if (live_stack->ContainsSorted(obj)) {
2523            LOG(ERROR) << "Object " << obj << " found in live stack";
2524          }
2525          if (heap_->GetLiveBitmap()->Test(obj)) {
2526            LOG(ERROR) << "Object " << obj << " found in live bitmap";
2527          }
2528          LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
2529                    << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
2530
2531          // Print which field of the object is dead.
2532          if (!obj->IsObjectArray()) {
2533            mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
2534            CHECK(klass != NULL);
2535            mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
2536                                                                      : klass->GetIFields();
2537            CHECK(fields != NULL);
2538            for (int32_t i = 0; i < fields->GetLength(); ++i) {
2539              mirror::ArtField* cur = fields->Get(i);
2540              if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
2541                LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
2542                          << PrettyField(cur);
2543                break;
2544              }
2545            }
2546          } else {
2547            mirror::ObjectArray<mirror::Object>* object_array =
2548                obj->AsObjectArray<mirror::Object>();
2549            for (int32_t i = 0; i < object_array->GetLength(); ++i) {
2550              if (object_array->Get(i) == ref) {
2551                LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
2552              }
2553            }
2554          }
2555
2556          *failed_ = true;
2557        }
2558      }
2559    }
2560  }
2561
2562 private:
2563  Heap* const heap_;
2564  bool* const failed_;
2565};
2566
2567class VerifyLiveStackReferences {
2568 public:
2569  explicit VerifyLiveStackReferences(Heap* heap)
2570      : heap_(heap),
2571        failed_(false) {}
2572
2573  void operator()(mirror::Object* obj) const
2574      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2575    VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
2576    obj->VisitReferences<true>(visitor, VoidFunctor());
2577  }
2578
2579  bool Failed() const {
2580    return failed_;
2581  }
2582
2583 private:
2584  Heap* const heap_;
2585  bool failed_;
2586};
2587
2588bool Heap::VerifyMissingCardMarks() {
2589  Thread* self = Thread::Current();
2590  Locks::mutator_lock_->AssertExclusiveHeld(self);
2591  // We need to sort the live stack since we binary search it.
2592  live_stack_->Sort();
2593  // Since we sorted the allocation stack content, need to revoke all
2594  // thread-local allocation stacks.
2595  RevokeAllThreadLocalAllocationStacks(self);
2596  VerifyLiveStackReferences visitor(this);
2597  GetLiveBitmap()->Visit(visitor);
2598  // We can verify objects in the live stack since none of these should reference dead objects.
2599  for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
2600    if (!kUseThreadLocalAllocationStack || *it != nullptr) {
2601      visitor(*it);
2602    }
2603  }
2604  return !visitor.Failed();
2605}
2606
2607void Heap::SwapStacks(Thread* self) {
2608  if (kUseThreadLocalAllocationStack) {
2609    live_stack_->AssertAllZero();
2610  }
2611  allocation_stack_.swap(live_stack_);
2612}
2613
2614void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
2615  // This must be called only during the pause.
2616  CHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
2617  MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2618  MutexLock mu2(self, *Locks::thread_list_lock_);
2619  std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
2620  for (Thread* t : thread_list) {
2621    t->RevokeThreadLocalAllocationStack();
2622  }
2623}
2624
2625void Heap::AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked() {
2626  if (kIsDebugBuild) {
2627    if (bump_pointer_space_ != nullptr) {
2628      bump_pointer_space_->AssertAllThreadLocalBuffersAreRevoked();
2629    }
2630  }
2631}
2632
2633accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
2634  auto it = mod_union_tables_.find(space);
2635  if (it == mod_union_tables_.end()) {
2636    return nullptr;
2637  }
2638  return it->second;
2639}
2640
2641accounting::RememberedSet* Heap::FindRememberedSetFromSpace(space::Space* space) {
2642  auto it = remembered_sets_.find(space);
2643  if (it == remembered_sets_.end()) {
2644    return nullptr;
2645  }
2646  return it->second;
2647}
2648
2649void Heap::ProcessCards(TimingLogger* timings, bool use_rem_sets) {
2650  TimingLogger::ScopedTiming t(__FUNCTION__, timings);
2651  // Clear cards and keep track of cards cleared in the mod-union table.
2652  for (const auto& space : continuous_spaces_) {
2653    accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
2654    accounting::RememberedSet* rem_set = FindRememberedSetFromSpace(space);
2655    if (table != nullptr) {
2656      const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
2657          "ImageModUnionClearCards";
2658      TimingLogger::ScopedTiming t(name, timings);
2659      table->ClearCards();
2660    } else if (use_rem_sets && rem_set != nullptr) {
2661      DCHECK(collector::SemiSpace::kUseRememberedSet && collector_type_ == kCollectorTypeGSS)
2662          << static_cast<int>(collector_type_);
2663      TimingLogger::ScopedTiming t("AllocSpaceRemSetClearCards", timings);
2664      rem_set->ClearCards();
2665    } else if (space->GetType() != space::kSpaceTypeBumpPointerSpace) {
2666      TimingLogger::ScopedTiming t("AllocSpaceClearCards", timings);
2667      // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
2668      // were dirty before the GC started.
2669      // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
2670      // -> clean(cleaning thread).
2671      // The races are we either end up with: Aged card, unaged card. Since we have the checkpoint
2672      // roots and then we scan / update mod union tables after. We will always scan either card.
2673      // If we end up with the non aged card, we scan it it in the pause.
2674      card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(),
2675                                     VoidFunctor());
2676    }
2677  }
2678}
2679
2680static void IdentityMarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>*, void*) {
2681}
2682
2683void Heap::PreGcVerificationPaused(collector::GarbageCollector* gc) {
2684  Thread* const self = Thread::Current();
2685  TimingLogger* const timings = current_gc_iteration_.GetTimings();
2686  TimingLogger::ScopedTiming t(__FUNCTION__, timings);
2687  if (verify_pre_gc_heap_) {
2688    TimingLogger::ScopedTiming t("(Paused)PreGcVerifyHeapReferences", timings);
2689    ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2690    size_t failures = VerifyHeapReferences();
2691    if (failures > 0) {
2692      LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
2693          << " failures";
2694    }
2695  }
2696  // Check that all objects which reference things in the live stack are on dirty cards.
2697  if (verify_missing_card_marks_) {
2698    TimingLogger::ScopedTiming t("(Paused)PreGcVerifyMissingCardMarks", timings);
2699    ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2700    SwapStacks(self);
2701    // Sort the live stack so that we can quickly binary search it later.
2702    CHECK(VerifyMissingCardMarks()) << "Pre " << gc->GetName()
2703                                    << " missing card mark verification failed\n" << DumpSpaces();
2704    SwapStacks(self);
2705  }
2706  if (verify_mod_union_table_) {
2707    TimingLogger::ScopedTiming t("(Paused)PreGcVerifyModUnionTables", timings);
2708    ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
2709    for (const auto& table_pair : mod_union_tables_) {
2710      accounting::ModUnionTable* mod_union_table = table_pair.second;
2711      mod_union_table->UpdateAndMarkReferences(IdentityMarkHeapReferenceCallback, nullptr);
2712      mod_union_table->Verify();
2713    }
2714  }
2715}
2716
2717void Heap::PreGcVerification(collector::GarbageCollector* gc) {
2718  if (verify_pre_gc_heap_ || verify_missing_card_marks_ || verify_mod_union_table_) {
2719    collector::GarbageCollector::ScopedPause pause(gc);
2720    PreGcVerificationPaused(gc);
2721  }
2722}
2723
2724void Heap::PrePauseRosAllocVerification(collector::GarbageCollector* gc) {
2725  // TODO: Add a new runtime option for this?
2726  if (verify_pre_gc_rosalloc_) {
2727    RosAllocVerification(current_gc_iteration_.GetTimings(), "PreGcRosAllocVerification");
2728  }
2729}
2730
2731void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
2732  Thread* const self = Thread::Current();
2733  TimingLogger* const timings = current_gc_iteration_.GetTimings();
2734  TimingLogger::ScopedTiming t(__FUNCTION__, timings);
2735  // Called before sweeping occurs since we want to make sure we are not going so reclaim any
2736  // reachable objects.
2737  if (verify_pre_sweeping_heap_) {
2738    TimingLogger::ScopedTiming t("(Paused)PostSweepingVerifyHeapReferences", timings);
2739    CHECK_NE(self->GetState(), kRunnable);
2740    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2741    // Swapping bound bitmaps does nothing.
2742    gc->SwapBitmaps();
2743    // Pass in false since concurrent reference processing can mean that the reference referents
2744    // may point to dead objects at the point which PreSweepingGcVerification is called.
2745    size_t failures = VerifyHeapReferences(false);
2746    if (failures > 0) {
2747      LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed with " << failures
2748          << " failures";
2749    }
2750    gc->SwapBitmaps();
2751  }
2752  if (verify_pre_sweeping_rosalloc_) {
2753    RosAllocVerification(timings, "PreSweepingRosAllocVerification");
2754  }
2755}
2756
2757void Heap::PostGcVerificationPaused(collector::GarbageCollector* gc) {
2758  // Only pause if we have to do some verification.
2759  Thread* const self = Thread::Current();
2760  TimingLogger* const timings = GetCurrentGcIteration()->GetTimings();
2761  TimingLogger::ScopedTiming t(__FUNCTION__, timings);
2762  if (verify_system_weaks_) {
2763    ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2764    collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
2765    mark_sweep->VerifySystemWeaks();
2766  }
2767  if (verify_post_gc_rosalloc_) {
2768    RosAllocVerification(timings, "(Paused)PostGcRosAllocVerification");
2769  }
2770  if (verify_post_gc_heap_) {
2771    TimingLogger::ScopedTiming t("(Paused)PostGcVerifyHeapReferences", timings);
2772    ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2773    size_t failures = VerifyHeapReferences();
2774    if (failures > 0) {
2775      LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
2776          << " failures";
2777    }
2778  }
2779}
2780
2781void Heap::PostGcVerification(collector::GarbageCollector* gc) {
2782  if (verify_system_weaks_ || verify_post_gc_rosalloc_ || verify_post_gc_heap_) {
2783    collector::GarbageCollector::ScopedPause pause(gc);
2784    PostGcVerificationPaused(gc);
2785  }
2786}
2787
2788void Heap::RosAllocVerification(TimingLogger* timings, const char* name) {
2789  TimingLogger::ScopedTiming t(name, timings);
2790  for (const auto& space : continuous_spaces_) {
2791    if (space->IsRosAllocSpace()) {
2792      VLOG(heap) << name << " : " << space->GetName();
2793      space->AsRosAllocSpace()->Verify();
2794    }
2795  }
2796}
2797
2798collector::GcType Heap::WaitForGcToComplete(GcCause cause, Thread* self) {
2799  ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
2800  MutexLock mu(self, *gc_complete_lock_);
2801  return WaitForGcToCompleteLocked(cause, self);
2802}
2803
2804collector::GcType Heap::WaitForGcToCompleteLocked(GcCause cause, Thread* self) {
2805  collector::GcType last_gc_type = collector::kGcTypeNone;
2806  uint64_t wait_start = NanoTime();
2807  while (collector_type_running_ != kCollectorTypeNone) {
2808    ATRACE_BEGIN("GC: Wait For Completion");
2809    // We must wait, change thread state then sleep on gc_complete_cond_;
2810    gc_complete_cond_->Wait(self);
2811    last_gc_type = last_gc_type_;
2812    ATRACE_END();
2813  }
2814  uint64_t wait_time = NanoTime() - wait_start;
2815  total_wait_time_ += wait_time;
2816  if (wait_time > long_pause_log_threshold_) {
2817    LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time)
2818        << " for cause " << cause;
2819  }
2820  return last_gc_type;
2821}
2822
2823void Heap::DumpForSigQuit(std::ostream& os) {
2824  os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
2825     << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
2826  DumpGcPerformanceInfo(os);
2827}
2828
2829size_t Heap::GetPercentFree() {
2830  return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / max_allowed_footprint_);
2831}
2832
2833void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
2834  if (max_allowed_footprint > GetMaxMemory()) {
2835    VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
2836             << PrettySize(GetMaxMemory());
2837    max_allowed_footprint = GetMaxMemory();
2838  }
2839  max_allowed_footprint_ = max_allowed_footprint;
2840}
2841
2842bool Heap::IsMovableObject(const mirror::Object* obj) const {
2843  if (kMovingCollector) {
2844    space::Space* space = FindContinuousSpaceFromObject(obj, true);
2845    if (space != nullptr) {
2846      // TODO: Check large object?
2847      return space->CanMoveObjects();
2848    }
2849  }
2850  return false;
2851}
2852
2853void Heap::UpdateMaxNativeFootprint() {
2854  size_t native_size = native_bytes_allocated_.LoadRelaxed();
2855  // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
2856  size_t target_size = native_size / GetTargetHeapUtilization();
2857  if (target_size > native_size + max_free_) {
2858    target_size = native_size + max_free_;
2859  } else if (target_size < native_size + min_free_) {
2860    target_size = native_size + min_free_;
2861  }
2862  native_footprint_gc_watermark_ = std::min(growth_limit_, target_size);
2863}
2864
2865collector::GarbageCollector* Heap::FindCollectorByGcType(collector::GcType gc_type) {
2866  for (const auto& collector : garbage_collectors_) {
2867    if (collector->GetCollectorType() == collector_type_ &&
2868        collector->GetGcType() == gc_type) {
2869      return collector;
2870    }
2871  }
2872  return nullptr;
2873}
2874
2875double Heap::HeapGrowthMultiplier() const {
2876  // If we don't care about pause times we are background, so return 1.0.
2877  if (!CareAboutPauseTimes() || IsLowMemoryMode()) {
2878    return 1.0;
2879  }
2880  return foreground_heap_growth_multiplier_;
2881}
2882
2883void Heap::GrowForUtilization(collector::GarbageCollector* collector_ran) {
2884  // We know what our utilization is at this moment.
2885  // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
2886  const uint64_t bytes_allocated = GetBytesAllocated();
2887  last_gc_size_ = bytes_allocated;
2888  last_gc_time_ns_ = NanoTime();
2889  uint64_t target_size;
2890  collector::GcType gc_type = collector_ran->GetGcType();
2891  if (gc_type != collector::kGcTypeSticky) {
2892    // Grow the heap for non sticky GC.
2893    const float multiplier = HeapGrowthMultiplier();  // Use the multiplier to grow more for
2894    // foreground.
2895    intptr_t delta = bytes_allocated / GetTargetHeapUtilization() - bytes_allocated;
2896    CHECK_GE(delta, 0);
2897    target_size = bytes_allocated + delta * multiplier;
2898    target_size = std::min(target_size,
2899                           bytes_allocated + static_cast<uint64_t>(max_free_ * multiplier));
2900    target_size = std::max(target_size,
2901                           bytes_allocated + static_cast<uint64_t>(min_free_ * multiplier));
2902    native_need_to_run_finalization_ = true;
2903    next_gc_type_ = collector::kGcTypeSticky;
2904  } else {
2905    collector::GcType non_sticky_gc_type =
2906        have_zygote_space_ ? collector::kGcTypePartial : collector::kGcTypeFull;
2907    // Find what the next non sticky collector will be.
2908    collector::GarbageCollector* non_sticky_collector = FindCollectorByGcType(non_sticky_gc_type);
2909    // If the throughput of the current sticky GC >= throughput of the non sticky collector, then
2910    // do another sticky collection next.
2911    // We also check that the bytes allocated aren't over the footprint limit in order to prevent a
2912    // pathological case where dead objects which aren't reclaimed by sticky could get accumulated
2913    // if the sticky GC throughput always remained >= the full/partial throughput.
2914    if (current_gc_iteration_.GetEstimatedThroughput() * kStickyGcThroughputAdjustment >=
2915        non_sticky_collector->GetEstimatedMeanThroughput() &&
2916        non_sticky_collector->NumberOfIterations() > 0 &&
2917        bytes_allocated <= max_allowed_footprint_) {
2918      next_gc_type_ = collector::kGcTypeSticky;
2919    } else {
2920      next_gc_type_ = non_sticky_gc_type;
2921    }
2922    // If we have freed enough memory, shrink the heap back down.
2923    if (bytes_allocated + max_free_ < max_allowed_footprint_) {
2924      target_size = bytes_allocated + max_free_;
2925    } else {
2926      target_size = std::max(bytes_allocated, static_cast<uint64_t>(max_allowed_footprint_));
2927    }
2928  }
2929  if (!ignore_max_footprint_) {
2930    SetIdealFootprint(target_size);
2931    if (IsGcConcurrent()) {
2932      // Calculate when to perform the next ConcurrentGC.
2933      // Calculate the estimated GC duration.
2934      const double gc_duration_seconds = NsToMs(current_gc_iteration_.GetDurationNs()) / 1000.0;
2935      // Estimate how many remaining bytes we will have when we need to start the next GC.
2936      size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
2937      remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
2938      remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
2939      if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
2940        // A never going to happen situation that from the estimated allocation rate we will exceed
2941        // the applications entire footprint with the given estimated allocation rate. Schedule
2942        // another GC nearly straight away.
2943        remaining_bytes = kMinConcurrentRemainingBytes;
2944      }
2945      DCHECK_LE(remaining_bytes, max_allowed_footprint_);
2946      DCHECK_LE(max_allowed_footprint_, GetMaxMemory());
2947      // Start a concurrent GC when we get close to the estimated remaining bytes. When the
2948      // allocation rate is very high, remaining_bytes could tell us that we should start a GC
2949      // right away.
2950      concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes,
2951                                         static_cast<size_t>(bytes_allocated));
2952    }
2953  }
2954}
2955
2956void Heap::ClearGrowthLimit() {
2957  growth_limit_ = capacity_;
2958  non_moving_space_->ClearGrowthLimit();
2959}
2960
2961void Heap::AddFinalizerReference(Thread* self, mirror::Object** object) {
2962  ScopedObjectAccess soa(self);
2963  ScopedLocalRef<jobject> arg(self->GetJniEnv(), soa.AddLocalReference<jobject>(*object));
2964  jvalue args[1];
2965  args[0].l = arg.get();
2966  InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_FinalizerReference_add, args);
2967  // Restore object in case it gets moved.
2968  *object = soa.Decode<mirror::Object*>(arg.get());
2969}
2970
2971void Heap::RequestConcurrentGCAndSaveObject(Thread* self, mirror::Object** obj) {
2972  StackHandleScope<1> hs(self);
2973  HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2974  RequestConcurrentGC(self);
2975}
2976
2977void Heap::RequestConcurrentGC(Thread* self) {
2978  // Make sure that we can do a concurrent GC.
2979  Runtime* runtime = Runtime::Current();
2980  if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self) ||
2981      self->IsHandlingStackOverflow()) {
2982    return;
2983  }
2984  JNIEnv* env = self->GetJniEnv();
2985  DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
2986  DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != nullptr);
2987  env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2988                            WellKnownClasses::java_lang_Daemons_requestGC);
2989  CHECK(!env->ExceptionCheck());
2990}
2991
2992void Heap::ConcurrentGC(Thread* self) {
2993  if (Runtime::Current()->IsShuttingDown(self)) {
2994    return;
2995  }
2996  // Wait for any GCs currently running to finish.
2997  if (WaitForGcToComplete(kGcCauseBackground, self) == collector::kGcTypeNone) {
2998    // If the we can't run the GC type we wanted to run, find the next appropriate one and try that
2999    // instead. E.g. can't do partial, so do full instead.
3000    if (CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false) ==
3001        collector::kGcTypeNone) {
3002      for (collector::GcType gc_type : gc_plan_) {
3003        // Attempt to run the collector, if we succeed, we are done.
3004        if (gc_type > next_gc_type_ &&
3005            CollectGarbageInternal(gc_type, kGcCauseBackground, false) != collector::kGcTypeNone) {
3006          break;
3007        }
3008      }
3009    }
3010  }
3011}
3012
3013void Heap::RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) {
3014  Thread* self = Thread::Current();
3015  {
3016    MutexLock mu(self, *heap_trim_request_lock_);
3017    if (desired_collector_type_ == desired_collector_type) {
3018      return;
3019    }
3020    heap_transition_or_trim_target_time_ =
3021        std::max(heap_transition_or_trim_target_time_, NanoTime() + delta_time);
3022    desired_collector_type_ = desired_collector_type;
3023  }
3024  SignalHeapTrimDaemon(self);
3025}
3026
3027void Heap::RequestHeapTrim() {
3028  // GC completed and now we must decide whether to request a heap trim (advising pages back to the
3029  // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
3030  // a space it will hold its lock and can become a cause of jank.
3031  // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
3032  // forking.
3033
3034  // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
3035  // because that only marks object heads, so a large array looks like lots of empty space. We
3036  // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
3037  // to utilization (which is probably inversely proportional to how much benefit we can expect).
3038  // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
3039  // not how much use we're making of those pages.
3040
3041  Thread* self = Thread::Current();
3042  Runtime* runtime = Runtime::Current();
3043  if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self) ||
3044      runtime->IsZygote()) {
3045    // Ignore the request if we are the zygote to prevent app launching lag due to sleep in heap
3046    // trimmer daemon. b/17310019
3047    // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
3048    // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
3049    // as we don't hold the lock while requesting the trim).
3050    return;
3051  }
3052  {
3053    MutexLock mu(self, *heap_trim_request_lock_);
3054    if (last_trim_time_ + kHeapTrimWait >= NanoTime()) {
3055      // We have done a heap trim in the last kHeapTrimWait nanosecs, don't request another one
3056      // just yet.
3057      return;
3058    }
3059    heap_trim_request_pending_ = true;
3060    uint64_t current_time = NanoTime();
3061    if (heap_transition_or_trim_target_time_ < current_time) {
3062      heap_transition_or_trim_target_time_ = current_time + kHeapTrimWait;
3063    }
3064  }
3065  // Notify the daemon thread which will actually do the heap trim.
3066  SignalHeapTrimDaemon(self);
3067}
3068
3069void Heap::SignalHeapTrimDaemon(Thread* self) {
3070  JNIEnv* env = self->GetJniEnv();
3071  DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
3072  DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != nullptr);
3073  env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
3074                            WellKnownClasses::java_lang_Daemons_requestHeapTrim);
3075  CHECK(!env->ExceptionCheck());
3076}
3077
3078void Heap::RevokeThreadLocalBuffers(Thread* thread) {
3079  if (rosalloc_space_ != nullptr) {
3080    rosalloc_space_->RevokeThreadLocalBuffers(thread);
3081  }
3082  if (bump_pointer_space_ != nullptr) {
3083    bump_pointer_space_->RevokeThreadLocalBuffers(thread);
3084  }
3085}
3086
3087void Heap::RevokeRosAllocThreadLocalBuffers(Thread* thread) {
3088  if (rosalloc_space_ != nullptr) {
3089    rosalloc_space_->RevokeThreadLocalBuffers(thread);
3090  }
3091}
3092
3093void Heap::RevokeAllThreadLocalBuffers() {
3094  if (rosalloc_space_ != nullptr) {
3095    rosalloc_space_->RevokeAllThreadLocalBuffers();
3096  }
3097  if (bump_pointer_space_ != nullptr) {
3098    bump_pointer_space_->RevokeAllThreadLocalBuffers();
3099  }
3100}
3101
3102bool Heap::IsGCRequestPending() const {
3103  return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
3104}
3105
3106void Heap::RunFinalization(JNIEnv* env) {
3107  // Can't do this in WellKnownClasses::Init since System is not properly set up at that point.
3108  if (WellKnownClasses::java_lang_System_runFinalization == nullptr) {
3109    CHECK(WellKnownClasses::java_lang_System != nullptr);
3110    WellKnownClasses::java_lang_System_runFinalization =
3111        CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
3112    CHECK(WellKnownClasses::java_lang_System_runFinalization != nullptr);
3113  }
3114  env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
3115                            WellKnownClasses::java_lang_System_runFinalization);
3116  env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
3117                            WellKnownClasses::java_lang_System_runFinalization);
3118}
3119
3120void Heap::RegisterNativeAllocation(JNIEnv* env, size_t bytes) {
3121  Thread* self = ThreadForEnv(env);
3122  if (native_need_to_run_finalization_) {
3123    RunFinalization(env);
3124    UpdateMaxNativeFootprint();
3125    native_need_to_run_finalization_ = false;
3126  }
3127  // Total number of native bytes allocated.
3128  size_t new_native_bytes_allocated = native_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes);
3129  new_native_bytes_allocated += bytes;
3130  if (new_native_bytes_allocated > native_footprint_gc_watermark_) {
3131    collector::GcType gc_type = have_zygote_space_ ? collector::kGcTypePartial :
3132        collector::kGcTypeFull;
3133
3134    // The second watermark is higher than the gc watermark. If you hit this it means you are
3135    // allocating native objects faster than the GC can keep up with.
3136    if (new_native_bytes_allocated > growth_limit_) {
3137      if (WaitForGcToComplete(kGcCauseForNativeAlloc, self) != collector::kGcTypeNone) {
3138        // Just finished a GC, attempt to run finalizers.
3139        RunFinalization(env);
3140        CHECK(!env->ExceptionCheck());
3141      }
3142      // If we still are over the watermark, attempt a GC for alloc and run finalizers.
3143      if (new_native_bytes_allocated > growth_limit_) {
3144        CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
3145        RunFinalization(env);
3146        native_need_to_run_finalization_ = false;
3147        CHECK(!env->ExceptionCheck());
3148      }
3149      // We have just run finalizers, update the native watermark since it is very likely that
3150      // finalizers released native managed allocations.
3151      UpdateMaxNativeFootprint();
3152    } else if (!IsGCRequestPending()) {
3153      if (IsGcConcurrent()) {
3154        RequestConcurrentGC(self);
3155      } else {
3156        CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
3157      }
3158    }
3159  }
3160}
3161
3162void Heap::RegisterNativeFree(JNIEnv* env, size_t bytes) {
3163  size_t expected_size;
3164  do {
3165    expected_size = native_bytes_allocated_.LoadRelaxed();
3166    if (UNLIKELY(bytes > expected_size)) {
3167      ScopedObjectAccess soa(env);
3168      env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
3169                    StringPrintf("Attempted to free %zd native bytes with only %zd native bytes "
3170                                 "registered as allocated", bytes, expected_size).c_str());
3171      break;
3172    }
3173  } while (!native_bytes_allocated_.CompareExchangeWeakRelaxed(expected_size,
3174                                                               expected_size - bytes));
3175}
3176
3177size_t Heap::GetTotalMemory() const {
3178  return std::max(max_allowed_footprint_, GetBytesAllocated());
3179}
3180
3181void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
3182  DCHECK(mod_union_table != nullptr);
3183  mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
3184}
3185
3186void Heap::CheckPreconditionsForAllocObject(mirror::Class* c, size_t byte_count) {
3187  CHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
3188        (c->IsVariableSize() || c->GetObjectSize() == byte_count));
3189  CHECK_GE(byte_count, sizeof(mirror::Object));
3190}
3191
3192void Heap::AddRememberedSet(accounting::RememberedSet* remembered_set) {
3193  CHECK(remembered_set != nullptr);
3194  space::Space* space = remembered_set->GetSpace();
3195  CHECK(space != nullptr);
3196  CHECK(remembered_sets_.find(space) == remembered_sets_.end()) << space;
3197  remembered_sets_.Put(space, remembered_set);
3198  CHECK(remembered_sets_.find(space) != remembered_sets_.end()) << space;
3199}
3200
3201void Heap::RemoveRememberedSet(space::Space* space) {
3202  CHECK(space != nullptr);
3203  auto it = remembered_sets_.find(space);
3204  CHECK(it != remembered_sets_.end());
3205  delete it->second;
3206  remembered_sets_.erase(it);
3207  CHECK(remembered_sets_.find(space) == remembered_sets_.end());
3208}
3209
3210void Heap::ClearMarkedObjects() {
3211  // Clear all of the spaces' mark bitmaps.
3212  for (const auto& space : GetContinuousSpaces()) {
3213    accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
3214    if (space->GetLiveBitmap() != mark_bitmap) {
3215      mark_bitmap->Clear();
3216    }
3217  }
3218  // Clear the marked objects in the discontinous space object sets.
3219  for (const auto& space : GetDiscontinuousSpaces()) {
3220    space->GetMarkBitmap()->Clear();
3221  }
3222}
3223
3224}  // namespace gc
3225}  // namespace art
3226