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