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